I have a "base class" in javascript that I call "main" in my example below. I want to use some methods and variables from the main class on all child classes that I create.
I have made two examples below with my current ideas. I suppose the the latter is preferred since I will create some instances of main, and I heard that prototype is useful when having more than one instance.
Should I go with any of these 2 methods, or try to create inheritance between the "classes"? If inheritance is preferred, please provide an example, since I don't know how ti implement that.
var main = (function(){
var out = function() {};
out.staticMethod = function(){
alert('hello world');
};
return out;
})();
var child = (function(main){
var out = function() {};
out.prototype.useMainFunction = function(){
main.staticMethod();
};
return out;
})(main);
var c = new child();
c.useMainFunction();
http://jsfiddle.net/mQPFJ/
var main = (function(){
var out = function() {};
out.prototype.publicMethod = function(){
alert('hello world');
};
return out;
})();
var child = (function(main){
var out = function() {};
out.prototype.useMainFunction = function(){
main.publicMethod();
};
return out;
})(new main());
var c = new child();
c.useMainFunction();
http://jsfiddle.net/mQPFJ/1/
I'm going to suggest a different approach:
function Main(){
this.message = "Parent";
}
Main.prototype.out = function(){
alert(this.message);
};
function Child(){
this.message = "Child";
};
Child.prototype = new Main();
var child = new Child();
child.out();
var main = new Main();
main.out();
This approach creates two classes using the function constructor. The first class main is given a property out, which is assigned a function. The second class Child has its prototype assigned to a new instance of Main, creating inheritance between the two classes.
Working Example: http://jsfiddle.net/8QW46/
In regards your question about which approach is best
I would suggest using the first method which does not use prototype. The reason I would suggest this is that your not actually using classes (in Javascript Classes are better described as object definitions). Your creating instances of a function. Usually prototype is used to add functions to all instances of a class.
Here is an example of what you will not be able to achieve using your approach, which would be available with classes/object definitions: http://jsfiddle.net/smmb3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With