JavaScript中 this 的指向

很多人都会被JavaScript中this的指向(也就是函数在调用时的调用上下文)弄晕,这里做一下总结:


首先,顶层的this指向全局对象。

函数中的this按照调用方法的不同,其指向也不同:

1、函数调用中的this指向全局对象

2、方法调用的函数中的this指向调用函数的对象:

function AnObject(name){
	this.name = name;
	this.getThis = function(){
		console.log(this);
    }
}
var ob = new AnObject('test');
ob.getThis(); //AnObject {name: "test"}
这里方法getThis被对象ob调用,故这里的this指向ob对象{name: "test"};


function getThis(){
    console.log(this);
}
getThis();  // Window
console.log(window.getThis); //function getThis(){......}
这里getThis是直接在顶层作用域下定义的一个方法,这里的this返回全局对象Window。我们都知道全局变量其实是作为全局对象的属性来实现的,这里的函数也是如此。用function getThis(){......}的写法等同于 var getThis = function() {......}。

而关于”顶层的this指向全局对象“,我的个人理解是:  顶层的代码段可以理解为全局作用域下的一个匿名函数,暨全局对象的一个方法,执行完毕后就销毁。那么这个方法中的this自然指向全局对象了。在REPL或者浏览器的控制台交互中,我们都可以感受到这样的性质。


3、构造函数中的this指向新创建的对象

function AnObject(name) {
    this.name = name;
    console.log(this);
}
var ob = new AnObject('another test');// AnObject {name: "another test"}

4、使用了apply、call、bind方法时,指向方法所指定的对象

function AnObject(name){
	this.name = name;
	this.getThis = function(){
		console.log(this);
    }
}
var ob = new AnObject('test');

ob.getThis.call({name: ' surprise '}); //Object {name: " surprise "}
ob.getThis.apply({name: ' surprise '});//Object {name: " surprise "}
var a = ob.getThis.bind({name: ' surprise '});
a();                                  //Object {name: " surprise "}
为了化简,这里忽略了”参数列表“这个参数,仅仅传入了新的作用域。可以看到,这时this的指向是我们所指定的对象。

posted @ 2017-02-28 20:22  贰拾肆樵  阅读(147)  评论(0编辑  收藏  举报