我正在寻找var self =这个替代方案.
var Animal = function(name){
this.name = name;
this.arr = [1,2,3,4];
this.inc = function(num){
return num + 1;
};
this.fireArr = function(){
var self = this;
this.arr.forEach(function(item){
console.log(self.inc(item));
});
};
};
var dog = new Animal("dog");
console.log(dog.fireArr());
Run Code Online (Sandbox Code Playgroud)
我的小提琴在这里.
http://jsfiddle.net/haradashinya/TtYpc/
你有什么主意吗?
提前致谢.
您可以将第二个参数设置为forEach,即this值.
this.arr.forEach(function(item){
console.log(this.inc(item));
}, this);
Run Code Online (Sandbox Code Playgroud)
您可以使用.bind()以确保使用正确的this值调用该函数:
function fireArr() {
this.arr.forEach(function(item){
console.log(this.inc(item));
}.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
但是imho self(that,_this)变量更容易理解,因为它直接表明不使用正常值this,尽管人们会期望它(例如在事件处理程序或jQuery中each()).特别是在长期功能上,你bind()最终看不到它,这很重要.此外,一些古老的浏览器不支持bind(),你需要填充它.
因此,对于任何就地函数表达式,我建议使用解除引用变量.
但是当你在某个地方定义了一个方法时,它可能会很有用,通常this用于指向当前对象,因为它在该上下文中很常见,然后该方法应该在其他地方使用.var self您可以而且应该使用bind简单和清晰的方法来代替包装器.您的示例提供了相当不错的演示(假设该inc方法使用了this关键字):
this.arr.forEach( this.inc.bind(this) );
Run Code Online (Sandbox Code Playgroud)
(虽然forEach()允许我们传递一个自定义this参数 - 例如事件attachers不)
| 归档时间: |
|
| 查看次数: |
1079 次 |
| 最近记录: |