this指向详细解析

213 阅读1分钟

指向总结

  • 全局中指向window

  • 函数预编译过程时指向window

  • call apply改变this指向(在上一篇博客中详细提及了他们两个的作用今天就不包含在实际案例之中)

  • 对象调用方法this的指向


实例分析

    var name= "222";
    var a = {
        name : "111",
        say : function() {
            console.log(this.name);
        }
    }
    var fun = a.say;
    fun();  
    a.say();  
    var b = {
        name : "333",
        say : function(fun){
            fun();     
        }
    }
    b.say(a.say);
    b.say = a.say;
    b.say(); 

按照之前所总结的答案很显然222、111、222、333。

不好理解的点可能在于b.say(a.say),这句语句相当于实现了把a中的方法放到b的say方法中调用,注意调用二字,b中say方法执行时只是在全局中执行了fun函数,而不是说b对象运行了fun函数中的代码。所以结果是222。

构造函数与函数区别

构造函数与函数this指向区别我们来看个案例

var a = 5;
function test() {
    console.log(a);
    a = 0;
    console.log(this.a);
    var a;
    console.log(a);
}
console.log(test()); // undefined、5、0

console.log(new test()) // undefined、undefined、0

这边又再次复习了一下与预编译的实现实现1时,函数中预编译环节this指向window所以输出5 执行2时,之前提及过构造函数生成对象时函数中会生成一个空的this对象(构造函数那篇有详细说明),那么这一次函数中this指向的是函数中的那个空this所以返回undefined。

ending...