的解决方案似乎只是有点太明显了,所以我想知道如果麻烦的是,你没有访问原始代码,你需要一个更动态的解决方案。
如果是这样,一个选项可能是用你自己的构造函数重载构造函数,并让它调用原来的,然后更新对象。
原始代码:
some.thing = function() {
this.somefn = function() { // this is the function that I need to fix
...
}
}
您的代码:
// cache a reference to the original constructor
var _thing = some.thing;
// your constructor
some.thing = function() {
// invoke the original constructor on the new object.
_thing.apply(this, arguments);
this.somefn = function() { /*your updated function*/ };
};
// maintain inheritance
some.thing.prototype = Object.create(some.thing.prototype);
// make an instance
var theThing = new some.thing();
现在你得到的原始构造函数和原型链的利益,但你正在将自己的功能注入到o中被创建的对象。
唯一的问题可能是您替换的原始函数可能会特别使用原始构造函数的变量作用域。如果是这样的话,就会有问题需要解决。
在调用你之前,可能会保留和调用你重写的原始方法。不知道这种情况是否需要这样做。
为什么里面的功能构造函数,而不是在构造函数的'.prototype'上?它是否需要构造函数中的变量访问? –
不......你只能为每个新创建的实例覆盖'obj.somefn'。 –
@FelixKling除非OP控制声明并且可以使其成为原型的属性... –