如何猴子修补对象的构造函数?
我想修补这个“控制器”对象的构造函数。但是我如何猴子修补构造函数,以便我仍然可以调用原始函数?这是我尝试过的。
// original
function Controller() {
this._tag = 'div';
}
Controller.prototype.tag = function() {
console.log(this._tag);
}
var c = new Controller();
c.tag(); // -> 'div', as expected
// patch attempt
var original = Controller;
Controller = function() {
original.apply(this);
this._tag = 'patched'; // patch
}
var c = new Controller();
c.tag(); // no method tag, prototype appears wiped...
I'd like to monkey patch the constructor for this 'Controller' object. But how do I monkey patch the constructor function so I can still call the original? This is what I've tried.
// original
function Controller() {
this._tag = 'div';
}
Controller.prototype.tag = function() {
console.log(this._tag);
}
var c = new Controller();
c.tag(); // -> 'div', as expected
// patch attempt
var original = Controller;
Controller = function() {
original.apply(this);
this._tag = 'patched'; // patch
}
var c = new Controller();
c.tag(); // no method tag, prototype appears wiped...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您似乎想做类似的事情:
现在所有实例都获得新的 tag 方法,并且如果需要(或将其放回),您仍然可以调用 oldTag 。
或者也许您想做类似的事情:
现在您有了一个包含所有旧方法的新构造函数。或者执行上述两项操作。只需用简单的英语说出您想做的事情即可。
You seem to want to do something like:
Now all instances get the new tag method and you can still call oldTag if you want (or put it back).
Or perhaps you want to do something like:
So now you have a new constructor with all the old methods. Or do both the above. Just use plain English to say what you want to do.
更简洁的方法不是猴子修补构造函数:将构造函数逻辑放在单独的
init
方法中,然后猴子修补/继承它。您还可以考虑使用构建器函数构建对象
The cleaner way is not monkey patching the constructor: put the constructor logic in a separate
init
method and monkey patch / inherit that instead.You can also consider building objects with a builder function
构造函数可以选择返回不同的
this
,它将覆盖new
语句本身生成的任何内容 - 这是您的示例更正和注释:Constructor functions may optionally return a different
this
, which will override whatever is generated by thenew
statement itself - here's your example corrected and annotated:You can try it here:
https://jsfiddle.net/mindplay/qc8Lf7ae/