我有一个上下文函数类型,定义如下:
var Context = function () {
this.run = function () {
method1();
method2();
}
var method1 = function () {
}
}
正如定义中明确指出的,method2 并未在上下文中定义。我需要 Context 的每个实例都传递此方法的实现。
var c = new Context();
// This does not work! because the call in run() function
// is not this.method2();
c.method2 = function () {
alert("injected method2");
};
c.run();
我需要将 method2() 保持在 run 状态,而不使用 this 对象,即 this.method2();嗯>
有什么解决办法吗?
最佳答案
如果您可以在创建Context
之前定义method2
,那么它将没有问题:
function method2() {
alert(2);
}
var c = new Context();
c.run();
关于创建对象后的 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42121135/