var self=这在原型上定义的方法中多次出现

var self=this multiple times in methods defined on the prototype?

本文关键字:方法 定义 self 原型 var      更新时间:2023-09-26

如果你必须对原型对象的方法使用 var self=this。你会在每个方法中写 var self=this 吗?

有没有办法避免在所有方法中编写 var self =this?

function Test () {
}
Test.prototype.method1 = function () {
 var self = this;
};
Test.prototype.method2 = function () {
 var self = this;
};
如果要

引入具有仍需要访问this上下文的函数文本的新上下文,则只需为this上下文创建别名。

function Test () {}
Test.prototype.method1 = function () {
  // This is fine.
  this.someProperty = 123;
  this.doSomething();
};
Test.prototype.method2 = function () {
  var self = this;
  var callback = function() {
    // The `this` here is no longer the same `this` as outside the function.
    self.someProperty = 456;
  };
  var anotherCallback = function() {
    // No reference to the class's `this` needed here.
    alert('Boo');
  };
  this.doAsyncThing(callback);
};

或者,您可以使用Function.prototype.bind强制this上下文:

var callback = function() {
  this.someProperty = 456;
}.bind(this);