The code below shows the closure pattern for creating objects.
function ClosurePattern() {
this.someMethod = function someMethod() {
console.log('foo');
}
}
var closurePattern = new ClosurePattern();
The code below shows the prototypal pattern for creating objects.
function PrototypalPattern() {}
PrototypalPattern.prototype = {
someMethod: function () {
console.log('foo');
}
}
var prototypalPattern = new PrototypalPattern();
Summary of the post:
- Advantages of the closure pattern:
- You can encapsulate private data.
- Advantages of the prototypal pattern:
- Going up the prototype chain is highly optimized in most JavaScript engines and happens fast.
- You save space, because no closure has to be created and someMethod is shared between objects (as opposed to added to each object).
- I also find it more readable: Instance variables are defined in the constructor, instance methods are defined in the prototype.
- Easier to analyze for tool builders. I feel for them, as they have to handle all of those JavaScript patterns and APIs out there.
Flattr
1 comment:
Great Information and post! It is very informative and suggestible for the user of solar energy, May I think it can be beneficial in coming days...
Post a Comment