彻底理解JavaScript中的this

this 是 JavaScript 语言的一个关键字。
它是函数运行时,在函数体内自动生成的一个对象,只能在函数体内使用。

函数的不同使用场合,this 有不同的值。总的来说,this 就是函数运行时所在的环境对象。下面分四种情况,详细讨论 this 的用法。

1. 作为对象的方法调用

当函数作为对象的方法被调用时, this 指向该对象:

let obj = {
    name : 'my name is obj',
    getName : function(){
        console.log(this.name)
    }
}

obj.getName()  // 'my name is obj'

2. 作为普通函数调用

当函数作为普通函数被调用时,this 指向全局对象(在浏览器的 JavaScript 里指向 window):

window.name = 'is me'

const getName = function() {
    return this.name
}

console.log( getName() )  // 'is me’

3. 构造器调用

当函数作为构造函数被使用时,this 指向返回的这个对象:

const MyClass = {
    this.name = 'className'
}

let obj = new MyClass()
console.log( obj.name ) // 'className'

4. call 或 apply 调用

const obj1= {
    name: 'TianGou Da',
    getName: function(){
        return this.name
    }
}
const obj2 = {
    name: 'TinaGou Ya'
}
console.log( obj1.getName() ) //  输出: TianGou Da
console.log( obj1.getName.call( obj2 ) )  // 输出:TinaGou Ya

参考文献:
阮一峰
[JavaScript设计模式和开发实践]

猜你喜欢

转载自www.cnblogs.com/CatFish/p/9810185.html