【发布时间】:2012-10-29 21:34:34
【问题描述】:
背景:我想重写一个库(我没有写)以避免闭包编译器使用高级选项生成警告。根据这个问题JavaScript “this” keyword and Closure Compiler warnings,答案是使用闭包重写代码。目的是避免使用关键字this(它会生成编译器警告)。
由于库有许多函数,我认为新闭包最好返回一个对象字面量。我想了解这是如何工作的以及任何可能的后果。因此,我写了以下(无意义的)示例作为学习经验(也在这里:jsFiddle):
var CurrencyObject = function(Amount) {
var money = Amount;
return {
"toCents": function() {
money *= 100;
return money;
},
"toDollars": function() {
money /= 100;
return money;
},
"currentValue": money // currentValue is always value of Amount
};
}; // end currencyObject
var c1 = CurrencyObject(1.99); // what's the difference if the syntax includes `new`?
alert('cents = ' + c1.toCents() + '\ncurrent money = ' + c1.currentValue + '\ndollars = ' + c1.toDollars() + '\ncurrent money = ' + c1.currentValue);
var c2 = CurrencyObject(2.99);
alert('cents = ' + c2.toCents() + '\ncurrent money = ' + c2.currentValue + '\ndollars = ' + c2.toDollars() + '\ncurrent money = ' + c2.currentValue);
alert('cents = ' + c1.toCents() + '\ncurrent money = ' + c1.currentValue + '\ndollars = ' + c1.makeDollars() + '\ncurrent money = ' + c1.currentValue);
Q1:为什么在调用 toCents 后 currentValue 没有更新? (我猜这是因为 currentValue 是一个文字(?),它在 CurrencyObject 首次执行时被初始化。如果是这种情况,那么返回属性 currentValue?)
Q2:这种语法(使用new)var c1 = new CurrencyObject(1.99); 不会以我可以检测到的方式改变代码的行为,但我认为存在差异。这是什么?
Q3:当 c2 被实例化时,是正在创建的函数的副本还是将 c1 和 c2共享相同的(功能)代码? (如果正在创建函数的副本,我应该进行哪些更改以避免这种情况?)
TIA
顺便说一句:如果有人想知道,对象文字中的符号会被引用以避免闭包编译器重命名它们。
【问题讨论】:
-
就像一个注释 -
makeDollars在你的小提琴中不是一个有效的调用 -
@ianpgall 感谢您的提醒。固定。
标签: javascript closures google-closure-compiler