0
我嘗試創建一個函數來在JavaScript中擴展「類」。擴展類和調用超級方法
function Extend(clazz, extend, info) {
var properties = {};
if(typeof(info) != 'undefined') {
properties.info = {
value: info
};
} else {
properties.info = {
value: {
name: 'Unknown',
author: 'Unknown',
version: '0.0.0'
}
};
}
clazz.prototype = Object.create(extend.prototype, properties);
eval(clazz.name + ' = clazz;');
}
這裏是超一流:
function Module() {
this.isRegistred = function isRegistred() {
return true;
};
this.start = function start() {
/* Override Me */
};
this.stop = function stop() {
/* Override Me */
};
this.kill = function kill() {
/* Override Me */
};
this.onJoin = function onJoin(user) {
/* Override Me */
};
this.onLeave = function onLeave(user) {
/* Override Me */
};
this.onDice = function onDice(event) {
/* Override Me */
};
this.onMessage = function onMessage(sender, text, receiver) {
/* Override Me */
};
};
在這裏擴展示例:
/**
@author Adrian Preuß <[email protected]>
@version 1.0.0
*/
Extend(function Welcome() {
this.onJoin = function onJoin(user) {
user.sendPrivateMessage('Welcome!');
};
}, Module, {
name: 'Welcome',
author: 'Adrian Preuß',
version: '1.0.0'
});
當我嘗試啓動類,並嘗試調用一個超級法(請參閱以下示例),「功能未知」出現錯誤:
var test = new Welcome();
test.onJoin(new User()); // It work's
console.log(test.info); // The info from the third args
if(test.isRegistred()) { // functtion is not defined
// Do something...
}
OK,幾個小技巧:在你的流量,哪裏是'功能模塊()'(即分配功能'isRegistered( )'這個'')叫? –
另一個提示:你想'Welcome.prototype'被鏈接到'Module.prototype',它實際上是空的。 –