覆盖函数而不删除静态属性 [英] Overriding a function without removing static properties
问题描述
如果我有这样的函数:
function a(){
console.log ');
}
,然后分配如下的静态属性:
a.static ='foo';但是说我要用这样的另一个函数覆盖函数:
$ b var old = a;
a = function(){
console.log('new');
old.call(this);
};
a.static // undefined
a
,它的静态属性丢失。有没有一个整洁的方式来保持静态属性没有循环和手动复制它们?
更新:
这是一个真实的世界场景:在Bootstrap jQuery插件中,作者赋予属性函数默认值如下:
$。fn.modal = function(){
// some code
};
$ .fn.modal.defaults = {// some object};
所以如果我想扩展原型,我通常会这样做:
var old = $ .fn.modal;
$ .fn.modal = function(){
//做我的事情
old.apply(this,arguments);
}
但这会使
$。fn.modal.defaults === undefined
这将打破功能,因为默认值丢失。我想知道是否有一个鬼祟的方式在javascript中更改只有函数,而不会失去静态属性。
解决方案不,你不能这样做。替换对象(函数)总是使用任何属性。
这里有两个解决方案,都涉及将属性从旧对象转移到新对象。 / p>
第一个(推荐)方法是复制属性,这可以方便地使用 $。extend
:
$。fn.plugin = $ .extend(function(){...},$ .fn.plugin);
第二个选项是动态设置新函数的原型为旧函数。例如,在一些浏览器中,这将工作:
var f = function(){...}
f .__ proto__ = $ .fn.plugin;
$ .fn.plugin = f;
但这是非标准的,可能会引起并发症;不要这样做。
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.
解决方案 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.
这篇关于覆盖函数而不删除静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!