Extend function - combine two functions?

Now Iโ€™m in some new territory, I didnโ€™t work with such things after a while.

What is the best way to have a Javascript class like

// In the parent instance function xyz() { var x = 1; } 

I want to set this in a class, and when the user extends the class, I want them to effectively extend this function. I know that I do not understand, but it was a long day. This is, for example, a user code.

 // In the child instance function xyz() { var y = 2; } 

The merger should result in:

 // In the merged instance function xyz() { var x = 1; var y = 2; } 

Am I smoking the wrong stuff or asking the wrong question?

+8
javascript jquery
source share
4 answers

You cannot โ€œcombineโ€ functions as they are described, but what you can do is to redefine one function to call both yourself and the new function (before or after the original).

 var xyz = function(){ console.log('xyz'); }; var abc = function(){ console.log('abc'); }; // and, elsewhere, if you want to merge: var orig = abc; abc = function(){ orig.call(this, arguments); xyz.call(this, arguments); }; 

Inclusion (this, arguments) is not required unless you care about the execution context or if the called function is without parameters. But for clarity, I have included what you can do if you want a parameterized method.

+8
source share

You put the question in jquery, so I assume you are using jquery. with jquery you can combine objects using jQuery.extend () .

 var object1 = { apple: 0, banana: {weight: 52, price: 100}, cherry: 97 }; var object2 = { banana: {price: 200}, durian: 100 }; /* merge object2 into object1 */ $.extend(object1, object2); 

or use a prototype chain to implement inheritance. eg:

 function a() { this.t1 = 1; this.sayMyName = function() { alert('a'); } } b.prototype = new a; b.prototype.constructor = b; function b() { this.t2 = 2; this.sayMyName = function() { alert('b'); } } var obj = new b(); alert(obj.t1); // this would say 1 obj.sayMyName(); // this would say b 
+8
source share

If you understand correctly, you can try renaming the original function and calling it in a new function:

 // In the parent instance function xyz() { var x = 1; } // In the child instance var old_xyz = xyz; function xyz() { var y = 2; old_xyz(); } 

Also works with class / method inheritance:

 MyClass.prototype.old_xyz = MyClass.prototype.xyz; MyClass.prototype.xyz = function () { this.old_xyz(); } 
0
source share
 const mergeFunctions = function () { let listOfFuncs = [] for (let func of arguments) { listOfFuncs.push(func) } return function () { for (let func of listOfFuncs) { func(arguments) } } } let x = function () { console.log("hello"); } let y = function () { console.log("world") } mergeFunctions(x, y)() ///////////////////// hello world 
0
source share

All Articles