Ran*_*ano 4 javascript v8 class spidermonkey
所以我一直在做一些类似 JavaScript 类的东西,比如
MyClass = function()
{
var x;
this.sayX = function()
{
alert(x);
}
}
Run Code Online (Sandbox Code Playgroud)
但我也看过
MyClass = function()
{
this.x = 0;
}
MyClass.prototype.sayX = function()
{
alert(this.x);
}
Run Code Online (Sandbox Code Playgroud)
最大的问题是,我是否仍然在当今的 JavaScript 引擎中浪费内存空间,或者他们是否能够看到我的方法中的重复并对其进行优化?我问的原因是因为我宁愿进行适当的数据隐藏,而不必绝对使用“this”作为前缀。
第一个的内存占用总是更大。将其prototype
视为所有实例都可以使用的共享方法包。这是有效的,因为您没有为每个实例创建一个新函数,而是重用内存中已有的方法。
好消息是你展示的两种方式可以结合起来。
MyClass = function () {
var x;
// public method with access
// to private variables
this.sayX = function () {
alert(x);
};
}
// method that doesn't need access to private variables
MyClass.prototype.sharedMethod = function () {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但就您处理小型代码库而言,您不必担心内存使用情况。你甚至可以使用像这样的模式
// everything will be created for every
// instance, but the whole thing is nicely
// wrapped into one 'factory' function
myClass = function () {
// private variables
var x;
// private methods
function doSomethingWithX() {}
// public interface
return {
sayX: function () {
alert(x);
},
publicMethod: function () { .. },
// ...
};
};
Run Code Online (Sandbox Code Playgroud)
注意,我特意把 myClass 改成了小写,因为它不再是构造函数,new
调用时也不需要使用了!
更新- 还有第三种模式非常适合您的需求:
MyClass = function (x, y, whatever) {
this._init.apply(this, arguments);
}
// The prototype creates a scope for data hiding.
// It also includes a constructor function.
MyClass.prototype = (function () {
var x; // private
return {
_init: function (x_in) {
x = x_in;
},
sayX: function () {
alert(x);
},
// ...
};
})();
Run Code Online (Sandbox Code Playgroud)