Overriding a function without removing static prop

2019-04-28 12:49发布

If I have a function like this:

function a() {
    console.log('a');
}

and then assign a static property like this:

a.static = 'foo';

But say I want to override the function with another function like this:

var old = a;

a = function() {
    console.log('new');
    old.call(this);
};

a.static // undefined

Since I assigned a new function to a, it’s static properties are lost. Is there a neat way to keep the static properties without looping and manually copying them?

Update:

Here’s a real world scenario: In Bootstrap jQuery plugins, the author assigns defaults to the property function like this:

$.fn.modal = function() {
    // some code
};

$.fn.modal.defaults = { // some object };

So if I want to "extend" the prototype I would normally do:

var old = $.fn.modal;

$.fn.modal = function() {
    // do my thing
    old.apply(this, arguments);
}

But that would make

$.fn.modal.defaults === undefined

This will break the functionality, because the defaults are lost. I was wondering if there a sneaky way in javascript to change only the function without losing the static properties.

1条回答
狗以群分
2楼-- · 2019-04-28 13:29

No, you cannot do this. Replacing the object (function) always takes any properties with it.

There are two solutions here, and both involve transferring the properties from the old object to the new one.

The first (recommended) approach is to copy the properties, which can be done conveniently with $.extend:

$.fn.plugin = $.extend(function() { ... }, $.fn.plugin);

The second option would be to dynamically set the prototype of the new function to be the old function. For example, in some browsers this would work:

var f = function() { ... };
f.__proto__ = $.fn.plugin;
$.fn.plugin = f;

However this is non-standard and might give rise to complications; don't do it.

查看更多
登录 后发表回答