【问题标题】:Javascript inheritance using node使用节点的 Javascript 继承
【发布时间】:2014-12-20 19:12:29
【问题描述】:

我想在我的子类中使用我父母的类方法。
在经典的 OOP 中,您只需扩展您的子类以利用您父母的功能,这可以使用原型吗?

这是我的文件结构:

父.js

var Parent = function(){
    this.add = function(num) {
        return num + 1;
    };
};

module.exports = Parent;

Child.js

var Parent = require("./parent.js"),
    util = require("util");

var Child = function() {

    this.sum = function(num) {
        // I want to be able to use Parent.add() without instantiating inside the class 
        // like this:
        console.log(add(num));
    };
};

util.inherits(Child, Parent);

module.exports = Child;

程序.js

var child = require("./child.js");

var Calculator = new child();

Calculator.sum(1);

显然,add() 在此处未定义。
我试过使用util.inherits,但我不确定这是不是正确的方法。

考虑到我希望有多个子类从我的父类继承,我还想问一下这在 JavaScript 中是否是一个好的设计模式?

【问题讨论】:

  • 你必须写成this.add(num)
  • 你还必须在Child构造函数中做Parent.call(this)

标签: javascript node.js oop design-patterns prototype


【解决方案1】:

您的代码有两个问题:

首先,正如@Pointy 在cmets 中提到的,Child.js 中的add 方法应使用this. 限定。这是因为使用add 会将其解析到根范围(浏览器中的window)。

其次,您使用this.add = function(...){...}Parent 中的add 方法独立绑定到每个特定实例。将它绑定到Parent 原型,你就会得到你想要的。

var Parent = function() {}
Parent.prototype.add = function(num) { return num + 1; }

函数Parent.prototype.add 将被推断为Parent 及其派生对象的所有实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多