Overriding a function without removing static properties

点点圈 提交于 2019-12-22 05:40:56

问题


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:


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.



来源:https://stackoverflow.com/questions/12686389/overriding-a-function-without-removing-static-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!