我想重新定义一个原型(prototype),但仍然使用原来的原型(prototype)函数。目的是将测试台调试代码添加到现有的生产原型(prototype)定义中。
// production definition
function tester(n) { this.name = n ; }
tester.prototype.getName = function() { return this.name; }
// debug override
if (typeof tester.prototype.getName === 'function') {
var f = tester.prototype.getName;
tester.prototype.getName = function () {
return f() + " (plus some more)";
};
}
// test
var tt = new tester('testing');
console.log(tt.getName()); // logs ' (plus some more)' but I want 'testing (plus some more)'
当然,我的生产原型(prototype)要复杂得多,我宁愿不在生产代码中嵌入我的测试平台代码。
提前非常感谢! - 约翰:)
最佳答案
您必须使用正确的 this
值和正确的参数调用 f
:
f.apply(this, arguments);
<小时/>
这似乎是一种非常脆弱的方法,因为它还要求您知道原始方法返回什么样的值以及调用代码正在用它做什么。
但我猜你只是针对非常具体的方法这样做。
关于javascript 使用现有原型(prototype)重新定义原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33702581/