问题
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