1. 程式人生 > >菜鳥關於js“this”的采坑記錄

菜鳥關於js“this”的采坑記錄

作用 調用 nbsp 方法 fine 是否 -s cto 詞法

一.對象中的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”的采坑記錄