Reputation: 10745
HI,
I have a JavaScript program that's written with object literal syntax:
var MyJsProgram = {
someVar: value1,
somevar2: value2,
init : function() {
//do some initialisation
},
libraryFunction : function() {
},
getStyle : function() {
},
extend : function() {
}
}
There can be multiple instances of this script running at once. Should I move the common methods in to the prototype object of the myJsProgram? If so, is this syntax correct?
var MyJsProgram = {
someVar: value1,
somevar2: value2,
init : function() {
//do some initialisation
},
//more methods/members here that are unique to each instance
}
myJsProgram.prototype = {
//all shared methods here
}
?
Upvotes: 2
Views: 206
Reputation: 30996
No, that syntax is not correct (no offense) ;)
You need to create an object for using its prototypes. That means that you need a constructor (which is a function in JavaScript). Applied to your problem:
var MyJsProgram = function (value1, value2) {
// "this" refers to the current instance of this object
this.someVar = value1;
this.someVar2 = value2;
// do some initialization
};
Create the new object like this:
var jsProgramInstance = new MyJsProgram(value1, value2);
Prototypes are instance members of those objects. They are defined like this:
MyJsProgram.prototype.someSharedMethodName = function () {
// do shared method stuff here
// (this.someVar and this.someVar2 are available here)
};
Use them like this (on your previously created instance):
jsProgramInstance.someSharedMethodName();
You should not do the following, since it overwrites the existing prototype properties that may exist (due to inheritance):
MyJsProgram.prototype = {
someSharedMethodName: function () {
// ...
},
// ...
};
Upvotes: 2
Reputation: 22438
First, make a function, from which you can make instances
// Make it a function, so you can make a new instance
var stdProgram = function(){};
// All shared methods go here
stdProgram.prototype = {
echo: function(message){
alert(message);
},
extend: function(key, value){
this[key] = value;
}
};
Then you could make your specific 'programs', actually just instances of the base class
// And here you can make instances for specific programs
var myFirstProgram = new stdProgram(),
mySecondProgram = new stdProgram();
myFirstProgram.extend('unique', function(){
alert('I am unique');
});
mySecondProgram.aVar = 'test';
To make sure everything works, try this:
myFirstProgram.unique(); // Should alert I am unique
mySecondProgram.unique(); // Should throw an error, unique is undefined
alert(mySecondProgram.aVar); // Should alert test
alert(myFirstProgram.aVar); // Should echo undefined
myFirstProgram.echo('hi'); // Should alert hi
mySecondProgram.echo('hi'); // Should alert hi
Upvotes: 3