0

Sample code:

// some library defines a function:

var func1 = function() {
    console.log('i am func1');
}

func1.magicProperty = 'bacon'; // with some properties


// i want to wrap the function to add some extra functionality:

(function() {
    var original = func1;

    func1 = function() {
       var result = original.apply(this,arguments);
        console.log('after func1');
        return result;
    };
})();


func1(); // yay it works!
console.log(func1.magicProperty); // but the properties are missing!!

How can I extend/wrap func1 but keep all its properties? Do I have to copy them all over to my new definition, or is there a better/faster way?


This is not quite the same as extending a [class] object because there's no usage of new here.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • possible duplicate of [Javascript object extending -](http://stackoverflow.com/questions/10430279/javascript-object-extending) –  Jun 18 '15 at 17:11
  • 1
    You could try storing the original function? http://stackoverflow.com/questions/14543271/programmatically-change-edit-javascript-function-using-javascript – Aleksander Azizi Jun 18 '15 at 17:13
  • @AleksanderAzizi that question does not address the issue of maintaining the properties on the function – mpen Jun 19 '15 at 00:21
  • @TinyGiant it's not a newable object I'm talking about – mpen Jun 19 '15 at 00:22
  • 1
    Yes, just copy them. – Bergi Jun 19 '15 at 02:23

1 Answers1

1

Try this

// some library defines a function:
var func1 = function() {
    console.log('i am func1');
}
func1.magicProperty = 'bacon'; // with some properties
// i want to wrap the function to add some extra functionality:
(function() {
    var original = func1;
    func1 = function() {
        var result = original.apply(this,arguments);
        console.log('after func1');
        return result;
    };
    for(var prop in original)
        func1[prop] = original[prop];
})();
func1(); // yay it works!
console.log(func1.magicProperty); // it will print 'bacon'

This is kind of copying

There is also some more sophisticated technique in JavaScript called "prototype" chaining

Refer Examples at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

From your example, using prototype

var func1 = function() {
    console.log('i am func1');
}
func1.magicProperty = 'bacon'; // with some properties
func1 = function() {
  var result = original.apply(this,arguments);
  console.log('after func1');
  return result;
}.prototype = func1;
func1();
console.log(func1.magicProperty);

here }.prototype = func1; immediately called because func1 is going to be overwritten

Dickens A S
  • 3,824
  • 2
  • 22
  • 45