【问题标题】:How to use Prototypes in Javascript如何在 Javascript 中使用原型
【发布时间】:2013-08-16 11:41:00
【问题描述】:

我下面的代码有什么问题?我收到错误 Object # has no method 'subtract'。

function result() {

}
result.prototype.add = function (a,b) {
var sub = this.subtract(a,b);
}
result.prototype.subtract = function (a,b) {
return a-b;
}

module.exports = result;

【问题讨论】:

  • 您还需要共享实际导致错误的代码
  • 我已经发布了上面导致错误的代码。
  • 该代码不会引发任何错误(在您将模块定义为哑对象以支持最后一行之后)。我猜这个错误是在您尚未发布的代码的其他部分中触发的
  • @user87267867:您需要向我们展示如何创建result 实例以及如何调用add 方法(您似乎做错了)。阅读this keyword
  • @Bergi result.prototype = new Validator(); function result() { } result.prototype.validate = function (a,b) { if ((a !=0) && (b !=0)) { return this.add(a,b); } }

标签: javascript oop prototype


【解决方案1】:

快速猜测是调用new 函数。

function result() {

}
result.prototype.add = function (a,b) {
   var sub = this.subtract(a,b);
}
result.prototype.subtract = function (a,b) {
   return a-b;
}

module.exports = new result();

【讨论】:

  • 嗯,那可能是你调用函数的方式有问题,你是怎么使用这个的?
猜你喜欢
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 2016-01-25
相关资源
最近更新 更多