hoyong

导航

理解 javascript 中的 this 在普通函数中调用,指向全局对象(转)

javascript中的this常见的三种情况:

1.在对象的方法中调用,this指向该对象

var obj = {
    a: 1,
    getA: function(){
        console.log( this === obj );
    }
}

obj.getA();     //true

 

2.在构造器中调用,this指向返回的对象

var Person = function(name){
    this.name = name;
};

var person1 = new Person('yiyi');
console.log(person1.name);     //'yiyi'



3.在普通函数中调用,this指向全局对象
当函数不作为对象的属性被调用时,也就是我们常说的普通函数方式,此时的this总是指向全局对象。

var obj = {
    a: 1,
    getA: function(){
        console.log ( this === obj );   // true
        var innerGet = function(){
            console.log ( this );
        };
        innerGet();     // window{...}
        return innerGet;
    }
};

/*
 * obj.getA 是一个函数,它执行后,即 obj.getA() 返回一个 innerGet 函数
 * 所以 obj.getA()() 这条语句相当于 innerGet()
 * 它没有作为对象的属性被调用,因此是普通函数
 * 也相当于 window.innerGet()
 */
obj.getA()();     // window{...}

   

在对象的方法中调用,this指向该对象

var obj = {
    a: 1,
    getA: (function(){
        console.log ( this === obj );   // true
        var innerGet = function(){
            console.log ( this );
        };
        innerGet();     // window{...}
        return innerGet;
    })()
};

/*
 * obj.getA 是一个立即执行函数,它已经执行并返回了 innerGet 函数
 * 因此这里的 innerGet 函数是作为 obj 对象的方法被调用的
 */
obj.getA();     // obj{...}

  

来看一个例子加深理解:
简化版 Function.prototype.bind 的实现
bind 方法的作用是指定函数内部的 this 指向

/*
 * 代码来自《javascript设计模式与开发实践》
 *
 * 为什么这里的 this 指向原函数?
 * 因为 bind 方法作为 function(){...} 对象的调用
 * 在对象的方法中调用,this 指向该对象
 */
Function.prototype.bind = function( context ){
    var self = this;        // 保存原函数
    return function(){      // 返回一个新的函数
        // 执行新的函数的时候,会把之前传入的 context
        // 当作新函数体内的 this
        return self.apply( context, arguments );
    }
};

var obj = {
    name: 'sven'
};

var func = function(){
    alert ( this.name );    // 输出:sven
}.bind( obj );

func();
---------------------
作者:web_wyj
来源:CSDN
原文:https://blog.csdn.net/web_wyj/article/details/79119141
版权声明:本文为博主原创文章,转载请附上博文链接!

posted on 2019-04-27 12:26  hoyong  阅读(339)  评论(0编辑  收藏  举报