Set Prototype Of The Module In Javascript
I've seen in some tests that using prototype methods increases the performance of the code execution and reduces the memory consumption, since methods are created per class, not pe
Solution 1:
The prototype property is the one you have to set on constructor functions. And the module pattern uses an IEFE (for local variables), which returns the "class" constructor.
var MyClass = (function() {
var _classProperty = "value1";
function MyClass() {
this.instanceProperty = …;
…
}
MyClass.prototype.prototypeProperty = "value2";
…
return MyClass;
})();
Then:
var instance = new MyClass;
console.log(instance.instanceProperty);
console.log(instance.prototypeProperty);
Solution 2:
You have to set the prototype of your constructor function:
var MyClass = function() {
var _classProperty = "value1";
this.classProperty = _classProperty;
};
MyClass.prototype = {
prototypeProperty : "value2"
};
var instance = new MyClass();
console.log(instance.classProperty); //value1
console.log(instance.prototypeProperty); //value2
EDIT
This is not an implementation of the module pattern but the constructor pattern. Neverless, it allows for private properties and methods (as far as JavaScript allows for that). But if your goal really was to implement the module pattern, take a look at Bergi's answer.
Post a Comment for "Set Prototype Of The Module In Javascript"