您的位置:首页 > 其它

this的值

2015-08-09 17:01 204 查看
在面向对象的编程中,this值很重要,且它的值取决于调用的模式

方法调用模式:this被绑定到该对象

var name = "outer";
var myObj = {
name : "inner",
getName : function () {
return this.name;
}
};
console.log(myObj.getName());   //inner,this指向myObj


函数调用模式:this被绑定到全局对象

var name = "outer";
var myObj = {
name : "inner",
getName : function () {
return function(){
return this.name;
};
}
};
console.log(myObj.getName()());  //outer,this指向window


解决办法为

var name = "outer";
var myObj = {
name : "inner",
getName : function () {
var that = this;
return function(){
return that.name;
};
}
};
console.log(myObj.getName()());  //inner


构造器调用模式:在函数前面使用new来调用,会创建连接到该函数的prototype属性的新对象,this会绑定到这个新对象上

function Dog (color) {
this.color = color;
}
Dog.prototype.getColor = function (){
return this.color;
};
var dog = new Dog("yellow");  //this绑定到dog上
console.log(dog.getColor());  //yellow


Apply/Call调用模式:函数拥有这两个方法,允许我们选择this的值

var name = "outer";
var myObj = {
name : "inner",
getName : function () {
return this.name;
}
};

console.log(myObj.getName());   //inner,this指向myObj
console.log(myObj.getName.apply(window));   //outer,this指向window


总结:在调用函数时,对参数this及arguments的搜索不遵守作用域链规则
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: