gpt4 book ai didi

javascript - 在闭包内声明的类与没有闭包的标准类

转载 作者:数据小太阳 更新时间:2023-10-29 05:26:30 25 4
gpt4 key购买 nike

通常我使用基于原型(prototype)的标准 OOP 方法,我的类看起来像这样

var std = function(){
this.log = function(msg){ console.log("want to be private. " + msg) };
};

std.prototype = {
logInfo: function(msg){
this.log(msg);
}
};

但在那种情况下,log 是公共(public)方法,任何人都可以使用它。但我想将其设为私有(private),但在原型(prototype)中声明的方法中仍然可用。为此,我们需要闭包。代码会改成这样

var closureStd = (function(){
var std = function(){};
var log = function(msg){ console.log("I'm really private, youhooo!" + msg) };

std.prototype = {
logInfo: function(msg){
log(msg);
}
};

return std;
})();

所以我的问题是:stdclosureStd 之间有什么区别,我需要付出什么代价才能从原型(prototype)调用私有(private)方法?

最佳答案

what is the difference between std and closureStd?

std 构造函数在每次调用时都会创建一个新方法,而 closureStd 则不会。你应该做到了

function std(){}
std.prototype = {
log: function(msg){ console.log("want to be private. " + msg) },
logInfo: function(msg){ this.log(msg); }
};

而且,当然(您已经知道)closureStd 中的 log 函数在 std 中存储在一个(私有(private))变量中> 实例在每个实例(或它们的原型(prototype))上都可以从外部访问(和覆盖)。在闭包中,它是范围链中的变量查找(可以假定为静态),而对于方法,它是对象(及其原型(prototype)链)的属性查找,这可能是动态的,但在现代引擎中同样得到了优化。

what is the price I need to pay to be able to call private methods from prototype?

没有。模块模式很常见且便宜,静态链中的变量查找非常快。我宁愿担心内存问题,因为您在构造函数方法中创建了如此多的方法实例。

关于javascript - 在闭包内声明的类与没有闭包的标准类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229411/

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