This - 面向对象编程。
1.全局环境下,this === window,如:
console.log(this === window);
2.构照函数中的this,指的是实例对象,如
var obj = function(p){
this.p = p;
}
obj.prototype.getP = function(){
return this.p;
}
var o = new obj("Hello World!");
console.log(o.p);
>>> Hello World!
console.log(o.getP());
>>> Hello World!注意点
1. 避免多层使用this
var obj = {
f1:function(){
console.log(this);
var f2 = function(){
console.log(this);
}();
}
}
obj.f1();
>>> Object
Window上面代码包含两层this,结果运行后,第一层指向该对象,第二层指向全局对象。
如何修改?改用一个指向外层this的变量_that
var obj = {
f1:function(){
console.log(this);
var _that = this;
var f2 = function(){
console.log(_that);
}();
}
}
obj.f1();
>>> Object
Object2. 避免数组处理方法中的this
var obj = {
v:'hello',
p:['a1','a2'],
f: function f(){
this.p.forEach(function(item){
console.log(this.v + ' ' + item);
});
}
}
obj.f();
>>> undefined a1
undefined a2出现undefined的原因是forEach方法的回调函数中的this,其实是指向window对象,因此取不到obj.v的值
解决方法一:使用中间变量。
var obj = {
v:'hello',
p:['a1','a2'],
var _that = this;
f:function f(){
this.p.forEach(function(item){
console.log(_that.v + ' ' + item);
});
}
}
obj.f();
>>> hello a1
hello a2解决方法二:将this当作foreach方法的第二个参数。
var obj = {
v:'hello',
p:['a1','a2'],
f:function f(){
this.p.forEach(function(item){
console.log(this.v + ' ' + item);
},this);
}
} 






网友评论文明上网理性发言 已有0人参与
发表评论: