Install prototype module in javascript

In some tests, I saw that using prototypes improves code execution performance and reduces memory consumption, since methods are created for each class, and not for each object. At the same time, I want to use the module template for my class, because it looks better and allows you to use private properties and methods.

The code diagram is as follows:

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

var object = {
  classProperty : _classProperty
};

object.prototype = {
  prototypeProperty = "value2"
}

return object;
}

But the prototype in this case does not work. I found that the reason is that prototypes are set for functions, not for the object. Therefore, I suggest that object.prototypeI should use instead object.__proto__.prototype. But it is __proto__not supported by all browsers and does not comply with ECMAScript5 rules.

, ?

0
2

prototype - , -. IEFE ( ), .

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

    function MyClass() {
        this.instanceProperty = …;
    }

    MyClass.prototype.prototypeProperty = "value2";

    return MyClass;
})();

:

var instance = new MyClass;
console.log(instance.instanceProperty);
console.log(instance.prototypeProperty);
+1

-:

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

FIDDLE

, . Neverless, ( JavaScript). , , .

+1

All Articles