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
}
?
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:
Create the new object like this:
Prototypes are instance members of those objects. They are defined like this:
Use them like this (on your previously created instance):
You should not do the following, since it overwrites the existing prototype properties that may exist (due to inheritance):