JavaScript中 this 的指向

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


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

函数中的this按照调用方法的不一样,其指向也不一样:浏览器

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

二、方法调用的函数中的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或者浏览器的控制台交互中,咱们均可以感觉到这样的性质。this


三、构造函数中的this指向新建立的对象
spa

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

四、使用了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的指向是咱们所指定的对象。
相关文章
相关标签/搜索