mpen
mpen

Reputation: 282845

How can I wrap a function but keep its properties?

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.

Upvotes: 0

Views: 156

Answers (1)

Dickens A S
Dickens A S

Reputation: 4054

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

Upvotes: 1

Related Questions