问题
I have one IIFE content which looks like this:
var A = (function() {
var method1 = function() {
alert("PARENT METHOD");
}
var method2 = function() {
method1();
}
return {
method1: method1,
method2: method2
}
})();
I want to override this method1 in another javascript object in a way when this method2 executes then it will call the overriden method1, not this original method1. Thanks in advance.
回答1:
You are going to need to use prototype in order to accomplish this the way you would like. Take a look at the example below.
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();
回答2:
If I understand what you're asking then you can just set the value of method2
(in your API object) to the overridden method (B
's method1
in this example). Since A
is created using IIFE, the object containing the overridden method must be declared before A
or you will wind up with a reference error.
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();
来源:https://stackoverflow.com/questions/51427062/how-to-override-a-javascript-iife-returned-method-in-an-object