问题:
过去两周我一直在研究的一个看似简单的问题(请放轻松,因为我是新手!):
在使用 Require.js 和 Revealing Module Pattern 时,如何巧妙地在 JavaScript 中实现继承?
例子:
这是一个示例模块,它是某种类型的“ Component
”的基类:
define('Component', [], function () {
"use strict";
var _privateVar = 10;
var _doPrivateThings = function () { /* do stuff */ };
var init = function () { /* do stuff */ };
var update = function () { /* do stuff */ };
return {
init : init,
update : update
};
});
接下来我想实现CakeComponent
应该继承所有内容Component
并允许我编辑/添加方法和属性:
define('CakeComponent', ['Component'], function (Component) {
"use strict";
// Setup inheritance
var CakeComponent = function() {}
CakeComponent.prototype = new Component();
// Add/edit methods/properties
CakeComponent.prototype.newMethod = function () { /* do stuff */ };
return {
init : CakeComponent.init,
update : CakeComponent.update,
newMethod : CakeComponent.newMethod
};
});
首先,我不确定这是否完全有意义,但其次,我的 CakeComponent 感觉有点恶心,因为现在我CakeComponent
到处都有这种冗余,我不得不“重新揭示” init
andupdate
方法。
我真的更喜欢这样的东西(我意识到这没有意义,它实际上只是伪代码):
define('CakeComponent', ['Component'], function (Component) {
"use strict";
this.extends(Component);
var newMethod = function () { /* do stuff */ };
return {
newMethod : newMethod
};
});
任何提示或建议将不胜感激。谢谢。
更多详细信息
- 也许我应该总是在
define
包装器中创建一个类对象?我见过人们这样做,但在我遇到这个问题之前似乎没有必要。 - 函数对象上的
.call()
方法在这种情况下是否有用?例如使用Component.call()
- @Bergi 请参见下文:
define([], function () {
"use strict";
var Component = function () {
var _privateVar = 10;
var _doPrivateThings = function () { /* do stuff */ };
this.init = function () { /* do stuff */ };
this.update = function () { /* do stuff */ };
};
return Component;
});