JS中this对象的理解

1.this在普通对象中的应用:

this指向调用它的对象

例子1:

var obj = {
name: "zhangsan",
id: 111222,
sex: "male",
introduce: function (){
console.log( this.name);
return this.name;
}
}
obj.introduce(); //张三 此时,this指向调用它的对象即obj。


例子2:

window.color = "red";
var o = {color: "blue"};

function sayColor(){
alert ( this.color);
}
sayColor(); //"red" 此时this指向调用它的全局window对象

o.saycolor = sayColor; //给o对象中添加sayColor方法
o.saycolor() //"blue" 此时this指向调用它的o对象


2.this在闭包中的应用:

匿名函数的执行环境具有全局性,因此其this通常指向window。但在以下写法中可能不是很明显

var name = "the window";
var obj = {
name: "my object",
getNameFunc : function(){
return function(){
return this.name;
}
}
};
alert(obj.getNameFunc()()); //"the window"
        解析:以上代码先创建了全局变量name,又创建了包含name属性的对象。对象中含包含getNameFunc方法。该方法返回一个匿名函数,而匿名函数又返回this.name.

    //执行过程,调用obj.getNameFunc()首先返回匿名函数function(){return this.name;},而匿名函数又返回this.name,因此调用obj.getNameFunc()()会立即返回字符串"my object".

如果我们想让this指向obj,需要做如下修改

var name = "the window";
var obj = {
name: "my object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
}
}
};
alert(obj.getNameFunc()()); //"my object"  将this强行绑定到变量that上,则that指向obj。
   

猜你喜欢

转载自blog.csdn.net/weixin_41658426/article/details/80164001