Set prototype of the module in Javascript

女生的网名这么多〃 提交于 2019-12-12 04:57:08

问题


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 per object. At the same time I want to use the module pattern for my class, since it looks nicer and allows to use private properties and methods.

The layout of the code is like the following:

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

var object = {
  classProperty : _classProperty
};

object.prototype = {
  prototypeProperty = "value2"
}

return object;
}

But the prototype in this case doesn't work. I've found that the reason is that prototypes are set for the functions, not the object. So I suppose that I should use object.__proto__.prototype instead of just object.prototype. But the __proto__ is not supported by all browsers and doesn't comply to ECMAScript5 rules.

So is there a better way to use prototypes in the module pattern object constructor?


回答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);



回答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

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.



来源:https://stackoverflow.com/questions/16896126/set-prototype-of-the-module-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!