一次被this支配之后的思考

开门见山

let name = 'panda'
let obj = {
    name: 'koala',
    getName() {
        return function() {
            return this.name
        }
    }
}
console.log(obj.getName()())    //undefined.

题目这样,我第一次回答的是koala。现在想了一下,估计是满脑子想吃波星冰乐给冲昏了脑子。
如果我改下!

let name = 'panda'
let obj = {
    name: 'koala',
    getName() {
        let that = this    //this -> that
        let name = 'koala'
        return function() {
            return that.name //this -> that
        }
    }
}
console.log(obj.getName()()) //koala

// 或者第二种,利用ES6
let name = 'panda'
let obj = {
    name: 'koala',
    getName() {
        let name = 'koala'
        return () => {
            return this.name
        }
    }
}
console.log(obj.getName()()) //koala

解题想法

我的理解,this其实跟其他语言的self应该是差不多。就是指代自己,比如说在一个function里面,那么this指向的就是这个func。

function colmugx() {
    //do something.
}

可能我讲的不清楚,就是this其实就是括号里的东西。

function colmugx(/** this */) {
    //do somethings
}

当然这是我的理解,我觉得应该就是这样的,所以刚刚那样取到的this并不是this。

浅谈this

只讲两种我懂的东西。

跟着new走

就是用new来创建对象的话,那么this就会跟着这个new

class Animal {
    constructor(name) {
        this.name = name;
    }
    func() {
        return this
    }
}
let a = new Animal('koala')
console.log(a.name) //koala
class Animal {
    constructor(name) {
        this.name = name;
    }
    func() {
        return this
    }
}
let a = new Animal('koala')
console.log(a.func()) //Animal { name: 'koala' }

ES6中括号函数的this

括号函数的this,不存在的!

说是不存在,实际上并不是说真的不见了,而是它会绑定到上一层函数中

func(()=> {
    //do somethings.
}/** ,this */)

而如果不是括号的话

func(function(/** this */){
    //do somethings.
})