This article describes a number of patterns to avoid name-space pollution. I listed the patterns below with part of the sample code that was given in the article.
My question is: is there any commonly accepted 'best' way? What are the considerations when choosing one for my project?
Direct Assignment
var myApp = {}
myApp.id = 0;
myApp.next = function() {
return myApp.id++;
}
Using Object Literal Notation
var myApp = {
id: 0,
next: function() {
return this.id++;
}
}
The Module Pattern
var myApp = (function() {
var id= 0;
return {
next: function() {
return id++;
},
};
})();
Namespace Argument
var myApp = {};
(function(context) {
var id = 0;
context.next = function() {
return id++;
};
})(myApp);
this as a Namespace Proxy
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
this.reset = function() {
id = 0;
}
}).apply(myApp);
The method I currently use
I used the following method in my own project. Is it bad?
function MyObj(){
this.someProperty = 'something';
}
MyObj.prototype.someFunction = function(){
this.someProperty =5;
}
myApp = new MyObj();
Aucun commentaire:
Enregistrer un commentaire