Javascript var self=在原型上定义的方法中多次使用?
如果必须对原型对象上的方法使用var self=this。您会在每个方法中编写var self=this吗 有没有办法避免在所有方法中写入var self=thisJavascript var self=在原型上定义的方法中多次使用?,javascript,Javascript,如果必须对原型对象上的方法使用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; }; 如果要引入新的上下文,且函数文本仍然需要访
function Test () {
}
Test.prototype.method1 = function () {
var self = this;
};
Test.prototype.method2 = function () {
var self = 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
强制执行此
上下文:
var callback = function() {
this.someProperty = 456;
}.bind(this);
您是否有您正在谈论的示例?如果您不想设置
self=this
,则始终可以使用bind
。但是,如果您正在讨论这个问题,您不能在外部仅设置一次self
。如果您可以发布一些代码,绑定示例将非常有用。它完全取决于代码的其余部分。某些函数允许您传递一个参数,该参数设置回调的此
值。像.forEach()
和.map()
这样的方法可以做到这一点,jQuery的$.ajax
也是如此。首先,您需要self
做什么?你能把你的代码的例子贴在你使用它的地方吗?嗯,我从来没有见过任何在原型方法上应用bind方法的代码。理论上这是可能的,但我不确定这是最好的方法。如何在bind(this)中再次获得原始引用?