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

一.对象中的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>

 

转载于:https://www.cnblogs.com/TBZW/p/10357902.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值