在Javascript中设置模块的原型 [英] Set prototype of the module in Javascript
问题描述
同时我想为我的类使用模块模式,因为它看起来更好,并允许使用私有属性和方法。
布局代码如下:
var MyClass = function(){
var _classProperty =value1;
var object = {
classProperty:_classProperty
};
object.prototype = {
prototypeProperty =value2
}
return object;
}
但是这种情况下的原型不工作。我发现原因是原型设置为函数,而不是对象。所以我想我应该使用 object .__ proto __。prototype
而不是只是 object.prototype
。但是 __ proto __
不是所有浏览器都支持的,并且不符合ECMAScript5规则。
更好的方式在模块模式对象构造函数中使用原型?
原型
属性是你必须设置的构造函数。模块模式使用IEFE(对于局部变量),它返回类构造函数。
var MyClass = (){
var _classProperty =value1;
function MyClass(){
this.instanceProperty = ...;
...
} $ b b
MyClass.prototype.prototypeProperty =value2;
...
return MyClass;
})();
然后:
var instance = new MyClass;
console.log(instance.instanceProperty);
console.log(instance.prototypeProperty);
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?
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);
这篇关于在Javascript中设置模块的原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!