JavaScript this

全局下this

非严格模式/严格模式 window

console.log("全局this", this);//window
console.log(this === window);//true

函数内this

非严格模式 window

function fun() {
    console.log("函数内this", this);//window
    console.log(this === window);//true
}
fun();

严格模式 undefined

function fun() {
    console.log("函数内this", this);//undefined
    console.log(this === window);//false
}
fun();

对象方法内this

非严格模式/严格模式 对象本身

var obj = {
    fun: function() {
        console.log("object方法内this", this);//obj
        console.log(this === obj);//true
    }
}
obj.fun();

构造函数内this

所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。

非严格模式/严格模式 新对象

function constructorFunction() {  
    this.x = 1;
    console.log(this); //constructorFunction {x: 1}
    console.log(this === window); //false
    console.log(this === obj); //false
    console.log(this.constructor); //ƒ constructorFunction() { ...... }
    console.log(typeof this); //object
    console.log(this instanceof Function); //false
}
var obj = new constructorFunction();
console.log(obj.x); //1

引申资料

其中说到用new操作符创建对象时发生的事情:

第一步: 创建一个Object对象实例。
第二步: 将构造函数的执行对象赋给新生成的这个实例。
第三步: 执行构造函数中的代码
第四步: 返回新生成的对象实例

apply调用下的this

apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。

非严格模式/严格模式 调用函数的参数

function test() {
    console.log(this);
}
var b = {};
var o = {
    m: test
};
o.m.apply();//window
o.m.apply(b);//对象b {}
o.m.apply(o);//对象o {m: ƒ}

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容