我正在 Node 中练习,无法理解如何从对象继承。 我想从我的路由器调用指定的 Controller 。 Controller 继承自基本 Controller 。但是当我尝试调用基本 Controller 方法时,我总是得不到定义。如何正确继承并调用parents方法?
我是新手,所以可能我没有掌握好基础知识。
我的代码:
路由器.js:
module.exports = function(app) {
app.get('/', function(req, res) {
var MainController = require('app/controller/mainController');
var controller = new MainController(req, res);
// Here I get undefined;
console.log(controller.getWidgets);
controller.index();
});
}
mainController.js:
var util = require('util');
var BaseController = require('./BaseController');
util.inherits(MainController, BaseController);
function MainController(req,res) {
this.index = function() {
// Here I want to use method from parent (BaseController)
// to get page widgets, also get undefined.
var widgets = this.getWidgets();
// console log also says there is no such method
console.log(this.getWidgets);
// then render page
res.render(...)
}
}
module.exports = MainController;
BaseController.js:
function BaseController() {
// example code
this.getWidgets = function() {
console.log('widgets are sent');
return 123;
}
}
module.exports = BaseController;
最佳答案
getWidgets 应该定义为原型(prototype)方法。
function BaseController() {
}
BaseController.prototype.getWidgets = function() {
console.log('widgets are sent');
return 123;
}
module.exports = BaseController;
关于javascript - Node.js 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534603/