javascript 使用现有原型(prototype)重新定义原型(prototype)

标签 javascript debugging prototype

我想重新定义一个原型(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);

详细了解thisapply .

<小时/>

这似乎是一种非常脆弱的方法,因为它还要求您知道原始方法返回什么样的值以及调用代码正在用它做什么。

但我猜你只是针对非常具体的方法这样做。

关于javascript 使用现有原型(prototype)重新定义原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33702581/

相关文章:

javascript - 是否安全地允许插入来自国外服务器的图像?

javascript - 在javascript中单击按钮的动画菜单中的问题

debugging - 可能是 Pandas 中的一个错误。我应该举报吗?如何?

debugging - 崩溃后查看内核日志

javascript - 使用javascript直接将剪贴板图像保存到客户端

javascript - 有没有办法用 AngularJS 创建自定义动画事件

xcode - 是否有 Xcode 在调试版本中自动设置的宏?

javascript - 对象属性在事件处理程序中未定义

javascript - 从一个对象到另一个 JavaScript (KineticJS) 的引用原型(prototype)方法

javascript - 当函数重新定义自身时,原型(prototype)会发生什么变化?