【发布时间】: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