使用 Node 的Javascript继承

标签 javascript node.js oop design-patterns prototype

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

这是我的文件结构:

Parent.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 中是否是一个很好的设计模式?

最佳答案

您的代码有两个问题:

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

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

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

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

关于使用 Node 的Javascript继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27583450/

相关文章:

javascript - 在JavaScript中访问JS引擎日期常量的方法?

javascript - 在嵌套数组概念方面需要帮助

java - 如何避免在函数(JAVA)中返回 NULL 值?

Javascript:setTimeout() - 需要帮助

javascript - 我尝试通过数据库验证数据以使用 Bootstrap 模式和 ajax 与 PHP 登录,但它不起作用

javascript - 将 JWT 从 AngularJS 发送到 Node.js

javascript - socket.io,使用 PHP session 作为带有 redis 的 socket.id

javascript - 自动递增对象id JS构造函数(静态方法和变量)

Objective-C继承;从父类(super class)调用重写的方法?

javascript - 需要隐藏 svg 的所有元素,除了从列表中选择的元素之外