javascript对象原型这个引用

时间:2013-04-09 11:07:52

标签: javascript object this

var x = (arg1, arg2) {
  this.y = arg1;
  this.z = arg2;
}

x.prototype.a = function() {
  var self = this;
  some_obj1.on('data', function() {
    self.y = 'new y value';
  });
}

x.prototype.b = function() {
  var self = this;
  some_obj2.on('data', function() {
    self.z = 'new z value';
  });
}

有没有办法将self声明为实例变量(显然不使用'this'),这样就不需要在每个函数中声明?因此,例如'a'的声明将是:

x.prototype.a = function() {
  ob2.on('data', function() {
    self.z = 'some new value';
  });
}

希望这个例子足够清楚,它没有经过测试(在提出问题时动态编写)和更多的伪代码,但应该明白这一点......

2 个答案:

答案 0 :(得分:2)

最好的办法是部分应用参数。以下是较新Function.prototype.bind的跨浏览器实现。使用以下实现的project.bind将使用本机Function.prototype.bind(如果可用)或自定义实现(如果本机实现不可用)。

<强>更新 我创建了一个有效的Fiddle

project = {};
project.bindJs_ = function(fn, selfObj, var_args) {
  if (!fn) {
    throw new Error();
  }

  if (arguments.length > 2) {
    var boundArgs = Array.prototype.slice.call(arguments, 2);
    return function() {
      // Prepend the bound arguments to the current arguments.
      var newArgs = Array.prototype.slice.call(arguments);
      Array.prototype.unshift.apply(newArgs, boundArgs);
      return fn.apply(selfObj, newArgs);
    };

  } else {
    return function() {
      return fn.apply(selfObj, arguments);
    };
  }
};
// A router for the native Function.prototype.bind
project.bindNative_ = function(fn, selfObj, var_args) {
  return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
};



   project.bind = function() {
       if (Function.prototype.bind &&
           Function.prototype.bind.toString().indexOf('native code') != -1) {
           project.bind = project.bindNative_;
       } else {
           project.bind = project.bindJs_;
       }
       return project.bind.apply(null, arguments);
    };

现在你可以这样做:

x.prototype.a = function() {
  ob2.on('data', project.bind(function() {
    // the this. object inside the function will now point to x.
    this.z = 'some new value';
  }, this, any, argument, you, want, to, pass));
}

答案 1 :(得分:2)

不,你不能。您需要以某种方式修改范围链,以避免使用this。稍微更简洁的方法是使用Function#bind指定this

x.prototype.a = function() {
  ob2.on('data', function() {
    this.z = 'some new value';
  }.bind(this));
}
相关问题