我已阅读 this answer和 IIFE但我似乎找不到解决问题的正确方法。
我这里有一个简单的类:
define(['jquery'], function($) {
// Need 'self' because someCallback() is being called with .call() and 'this' changes
var self;
function Foo(number) {
self = this;
this.someNumber = number;
}
Foo.prototype = {
someCallback: function () {
//Use self because 'this' changes to a DOM element
var num = self.someNumber;
//Do something with the num
return num * 2;
}
};
return Foo;
});
和 someCallBack()
由 jQuery 插件使用 .call()
调用。因此,上下文发生了变化,因此使用了 self
变量。
但是,这是错误的,因为:
define(['foo'], function(Foo) {
describe('context question', function () {
var foo1 = new Foo(1);
var foo2 = new Foo(2);
it('"this" should work', function () {
var call1 = foo1.someCallback.call(this); // 4
var call2 = foo2.someCallback.call(this); // 4
expect(call2).toBe(4); // Only works because it is 'new' last
expect(call1).toBe(2); // Fails because 'self' is taken from foo2
});
});
});
我应该如何包装 self
变量才能使这段代码正常工作?
最佳答案
您可能只使用 revealing module pattern并将其声明为“全局”变量(模块本地):
define(['jquery'], function($) {
var someNumber;
function Foo(number) {
someNumber = number;
}
Foo.prototype = {
someCallback: function () {
return someNumber * 2;
}
};
return Foo;
});
关于javascript - 如何在 javascript 闭包中将 'this' 保留在类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35514527/