var self=此模式的备选方案

alternative for the var self = this pattern

本文关键字:方案 模式 self var      更新时间:2023-09-26

我正在寻找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());

我的小提琴在这儿。

http://jsfiddle.net/haradashinya/TtYpc/

你知道吗?

提前谢谢。

您可以将第二个参数设置为forEach,即this值。

this.arr.forEach(function(item){
  console.log(this.inc(item));
}, this);

您可以使用.bind()来确保使用正确的this值调用函数:

function fireArr() {
    this.arr.forEach(function(item){
        console.log(this.inc(item));
    }.bind(this));
}

但是,imho selfthat_this)变量更容易理解,因为它直接声明没有使用正常的this值,尽管人们会期望它(例如在事件处理程序或jQuery的each()中)。尤其是在长函数上,当您最终看不到bind()时,这一点非常重要。此外,一些古老的浏览器不支持bind(),您需要填充它

因此,对于任何就地函数表达式,我建议使用解引用变量。

但是,当您在某个地方定义了一个方法时,它可能会非常有用,通常使用this来指向当前对象,因为它在该上下文中很常见,然后应该在其他地方使用该方法。为了简单明了,您可以也应该使用bind来代替var self包装器。您的示例提供了一个非常好的演示(假设inc方法使用了this关键字):

this.arr.forEach( this.inc.bind(this) );

(尽管forEach()允许我们传递自定义this参数-例如,事件附件不允许)

在您的示例中,inc函数不使用this值,因此它不需要是一个方法。您可以将其定义为本地函数:

var Animal = function ( name ) {
    this.name = name;
    this.arr = [ 1, 2, 3, 4 ];
    var inc = function ( num ) {
        return num + 1;
    };
    this.fireArr = function () {
        this.arr.forEach(function ( item ) {
            console.log( inc( item ) );
        });
    };
};