gpt4 book ai didi

JavaScript 类内存使用

转载 作者:行者123 更新时间:2023-11-29 10:24:40 25 4
gpt4 key购买 nike

所以我一直在做一些类似 JavaScript 类的东西,比如

MyClass = function()
{
var x;

this.sayX = function()
{
alert(x);
}
}

但我也见过

MyClass = function()
{
this.x = 0;
}

MyClass.prototype.sayX = function()
{
alert(this.x);
}

最大的问题是,我是否还在浪费今天的 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 () {
// ...
}

但就您处理的小代码库而言,您不应该担心内存使用。您甚至可以使用像

这样的模式
// 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 () { .. },
// ...
};
};

请注意,我有意将 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);
},
// ...
};
})();

关于JavaScript 类内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4116779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com