i try to create an Function to extend a "Class" in 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;');
}
Here is the Super-Class:
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 */
};
};
And here the Extended sample:
/**
@author Adrian Preuß <a.preuss@ChannelApp.de>
@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'
});
When i try to initiate the class and try to call a super-method (see the following sample), an error appears with "function is unknown":
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...
}
You are trying to extend by prototype
, but you don't use prototype
in the first place.
When you assign a function to a class using this
, you assign the function to the instance, not to the class itself. If you look at Module.prototype
, it'll not contain any of your methods.
The clean way to solve your problem is to declare your functions to the prototype
:
function Module() {}
Module.prototype.isRegistred = function isRegistred() {
return true;
};
// And so on...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.