Skip to content Skip to sidebar Skip to footer

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.

varMyClass = (function() {
    var _classProperty = "value1";

    functionMyClass() {
        this.instanceProperty = …;
        …
    }

    MyClass.prototype.prototypeProperty = "value2";
    …

    returnMyClass;
})();

Then:

var instance = newMyClass;
console.log(instance.instanceProperty);
console.log(instance.prototypeProperty);

Solution 2:

You have to set the prototype of your constructor function:

varMyClass = function() {
    var _classProperty = "value1";
    this.classProperty = _classProperty;
};

MyClass.prototype = {
    prototypeProperty : "value2"
};

var instance = newMyClass();
console.log(instance.classProperty); //value1console.log(instance.prototypeProperty); //value2

FIDDLE

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"