All are useful and none are wrong.. If I only needed one notebook in my app, I'd lean towards using 2) since it neatly encapsulates all properties within its defining closures. For multiple notebook "instances" I like 5) simply because I can lock generic properties into the prototype object, making the constructor cleaner and more efficient
Next time I'll talk about how to employ object inheritance with each methodology.
1. Simple Object Literal
myApp.notepad = {};
myApp.notepad.writeable = true;
myApp.notepad.font = 'helvetica';
myApp.notepad.setFont = function(theFont) {
myApp.notepad.font = theFont;
}2. Nested Object Literal
myApp.notepad = {
writeable: true,
font: 'helvetica',
setFont: function(theFont) {
this.font = theFont;
}
}
3. Constructor using Object Literal
myApp.Notepad = function(defaultFont) {
var that = {};
that.writeable = true;
that.font = defaultFont;
that.setFont = function(theFont) {
that.font = theFont;
}
return that;
return that;
}
myApp.notepad1 = myApp.Notepad('helvetica');
4. Simple Constructor for new
myApp.Notepad = function(defaultFont) {
this.writeable = true;
this.font = defaultFont;
this.setFont = function(theFont) {
this.font = theFont;
}
}
myApp.notepad1 = new myApp.Notepad('helvetica');
this.writeable = true;
this.font = defaultFont;
this.setFont = function(theFont) {
this.font = theFont;
}
}
myApp.notepad1 = new myApp.Notepad('helvetica');
5. Prototype with Constructor for new
this.font = defaultFont;
}
myApp.Notepad.prototype.writeable = true;
myApp.Notepad.prototype.setFont = function(theFont) {
this.font = theFont;
}
myApp.notepad1 = new myApp.Notepad('helvetica');
No comments:
Post a Comment