【问题标题】:Multiple inheritance with node.js utils.inherits?node.js utils.inherits 的多重继承?
【发布时间】:2013-09-19 01:54:20
【问题描述】:

您好,我是 node 新手,我正在尝试构建一个 MVC 应用程序。对于控制器和模型,我可以使用 utils.inherits 创建基类和子类。对于视图,我想创建 3 个级别:基础、html/json、模块。在每一层都有一个名为construct的函数,在创建实例时需要调用它,并且在顶部调用它应该链接回每一层。

基础视图:

function Base_view( ) {
    this._response = null;
};

Base_view.prototype.construct = function( res ) {
    this._response = res;
};

HTML 视图:

var util = require( 'util' ),
    Base_view = require( './view' );

function Html_view( ) {
    Base_view.apply( this, arguments );
}

util.inherits( Html_view, Base_view );

Html_view.prototype.construct = function( res, name ) {
    this.constructor.super_.prototype.construct.apply( this, arguments );
};

模块视图:

var util = require( 'util' ),
    Html_view = require( './../base/html' );

function Main_view( ) {
    Html_view.apply( this, arguments );
}

util.inherits( Main_view, Html_view );

Main_view.prototype.construct = function( ) {
    this.constructor.super_.prototype.construct.apply( this, arguments );
};

模块视图中的这一行会产生一个未定义的错误:

this.constructor.super_.prototype.construct.apply( this, arguments );

如果我只在正确调用父类构造方法时进行子类化。如何使用它进行多次扩展?

在这篇文章中:util.inherits - alternative or workaround 有一个修改后的 utils.inherits 方法,看起来它应该这样做,但我不知道如何使用它?我已经尝试在模块中要求这两个类并将所有三个类都作为参数。

谢谢!

【问题讨论】:

  • 通常你显式地调用你的父原型函数。所以在Main_view.construct 我会做Html_view.prototype.construct.apply() 然后在Html_view 做Base_view.prototype.construct.apply()。显式调用您父母的方法。当然,您应该使用将对象定义为构造函数的函数,而不是单独的方法。

标签: node.js inheritance prototype


【解决方案1】:

通过删除我添加虚假可调用构造函数并使用 func def 作为构造函数的尝试使其工作。忽略 util 要求,它只是包含一些标准 util 函数和我自己的一些函数的包装器。它所做的只是调用内置方法。

/controllers/base/view.js:

function Base_view( res ) {
    this._response = res;
};

/controllers/base/html.js:

var util = require( '../../helpers/util' ),
    Base_view = require( './view' );

function Html_view( res, name ) {
    Base_view.apply( this, arguments );
    this._name = name;
};

util.inherits( Html_view, Base_view );

/controllers/main/html.js:

var util = require( '../../helpers/util' ),
    Html_view = require( './../base/html' );

function Main_view( res, name ) {
    Html_view.apply( this, arguments );
};

util.inherits( Main_view, Html_view );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2012-03-07
    • 2012-06-02
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多