分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

菜鸟关于js“this”的采坑记录

发布时间:2023-09-06 02:32责任编辑:沈小雨关键词:js

一.对象中的this

这里主要讨论函数的两种调用模式,函数模式与方法模式,以函数模式调用时,this多指undefined或window(是否使用严格模式)

定义在全局变量中的函数用函数模式调用,this指向window或undefine

function example (){ ???console.log(this)//undefined}

定义为对象方法的函数用方法模式调用,this指定为这个对象

let xiaoming = { ???name:"小明", ???hello: function(){ ???????console.log("Hello,"+this.name)//this指向对象xiaoming ???}}xiaoming.hello();//Hello,小明

值得一提的是,如果对象的方法内部包含了其他函数(比如return了一个函数),该函数以函数模式调用,this指向window或undefine

let xiaoming = { ???name:"小明", ???hello: function(){ ?????????return function(){console.log("Hello,"+this.name)}//用函数模式调用 ???}}xiaoming.hello()();//Hello, ?

二.class中的this

在class中,公用方法中的this指向所在的类

class Students { ???constructor(name){ ???????this.name = name ???} ???hello (){ ???????console.log("Hello,"+this.name) ???}}let xiaoming = new Students("小明");xiaoming.hello();//Hello,小明

如果该方法包含了一个其他函数,被包含的函数中this指向window或undefined

class Students { ???constructor(name){ ???????this.name = name ???} ???hello (){ ???????return function(){ ???????????console.log("Hello,"+this.name) ???????} ???}}let xiaoming = new Students("小明");xiaoming.hello()();//undefined

ES6标准中新引进了箭头函数,箭头函数的this会根据词法作用域找到父级函数的this并和他保持一致

class Students { ???constructor(name){ ???????this.name = name ???} ???hello (){ ???????return ()=>{ ???????????console.log("Hello,"+this.name)//这里的this指向父级函数的this,即hello()的this ???????} ???}}let xiaoming = new Students("小明");xiaoming.hello()();//Hello,小明

三.React中的this

import React, { Component } from ‘react‘class ExampleApp extends Component {examplemethod(){console.log(this)}render(){ ?????return(
?????????????<div onClick={this.examplemethod}>测试</div>
}
)}}

按照之前说的内容,我们点击按钮,应该得到ExampleApp组件,可是实际上,我们会得到undefined,这是因为React在调用该函数时不通过常规的方法调用,而是通过函数调用导致this指向了window或undefined,对于这种情况有两种纠正方法

1.使用箭头函数

example = () => { ???console.log(this)}

2.在调用的按钮上用bind绑定this

<div onClick={this.examplemethod.bind(this)}>测试</div>

菜鸟关于js“this”的采坑记录

原文地址:https://www.cnblogs.com/TBZW/p/10357902.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved