如何覆盖对象中的 javascript IIFE 返回方法?
How to override a javascript IIFE returned method in an object?
我有一个 IIFE 内容,如下所示:
var A = (function() {
var method1 = function() {
alert("PARENT METHOD");
}
var method2 = function() {
method1();
}
return {
method1: method1,
method2: method2
}
})();
我想在另一个 javascript 对象中覆盖此方法 1,当此方法 2 执行时,它将调用覆盖的方法 1,而不是此原始方法 1。提前致谢。
您将需要使用原型才能按照您希望的方式完成此操作。看看下面的例子。
var A = (function() {
var api = function(){}
api.prototype.method1 = function() {
console.log("PARENT METHOD");
}
api.prototype.method2 = function() {
this.method1();
}
return new api();
})();
A.method2();
A.method1 = function() { console.log('child method');}
A.method2();
如果我明白你在问什么,那么你可以将 method2
的值(在你的 API 对象中)设置为覆盖的方法(B
的 method1
在这个例子中)。由于 A
是使用 IIFE 创建的,因此必须在 A
之前声明包含重写方法的对象,否则会出现引用错误。
var B = {
method1: function() {
console.log('This is method2 in B!');
}
}
var A = (function() {
var method1 = function() {
alert("PARENT METHOD");
}
var method2 = function() {
method1();
}
return {
method1: method1,
method2: B.method1
}
})();
//call A.method2
A.method2();
我有一个 IIFE 内容,如下所示:
var A = (function() {
var method1 = function() {
alert("PARENT METHOD");
}
var method2 = function() {
method1();
}
return {
method1: method1,
method2: method2
}
})();
我想在另一个 javascript 对象中覆盖此方法 1,当此方法 2 执行时,它将调用覆盖的方法 1,而不是此原始方法 1。提前致谢。
您将需要使用原型才能按照您希望的方式完成此操作。看看下面的例子。
var A = (function() {
var api = function(){}
api.prototype.method1 = function() {
console.log("PARENT METHOD");
}
api.prototype.method2 = function() {
this.method1();
}
return new api();
})();
A.method2();
A.method1 = function() { console.log('child method');}
A.method2();
如果我明白你在问什么,那么你可以将 method2
的值(在你的 API 对象中)设置为覆盖的方法(B
的 method1
在这个例子中)。由于 A
是使用 IIFE 创建的,因此必须在 A
之前声明包含重写方法的对象,否则会出现引用错误。
var B = {
method1: function() {
console.log('This is method2 in B!');
}
}
var A = (function() {
var method1 = function() {
alert("PARENT METHOD");
}
var method2 = function() {
method1();
}
return {
method1: method1,
method2: B.method1
}
})();
//call A.method2
A.method2();