- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
通常我使用基于原型(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;
})();
所以我的问题是:std
和 closureStd
之间有什么区别,我需要付出什么代价才能从原型(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/
我在一个 twig 模板中使用 Assetic 来指定要从我的包中使用的 2 个 JS 文件 { % javascripts '@JiraExtendedReportsBund
我正在做一个 VS 包,它在菜单中有一个 DynamicItemStart 按钮。我在 VS 启动时加载动态按钮的内容没有任何问题,但我试图在某些事件(例如打开项目)之后向其内容添加更多命令。我将新命
需求是从plsql调用java方法,我可以通过loadjava命令来实现它。我遵循的步骤是: 第 1 步:创建 Java Class/jar 文件并将其放置在 Unix 机器上 第2步:将Java C
我是一名优秀的程序员,十分优秀!