Background: I want to rewrite a library (which I did not write) to avoid having the Closure Compiler generate warnings with the advanced option. Per this question JavaScript “this” keyword and Closure Compiler warnings the answer was to rewrite the code using a closure. The intent is to avoid using the keyword this (which generates the compiler warnings).
As the library has a number of functions, I though it would be best for the new closure to return an object literal. I want to understand how this works and any possible ramifications. I therefore wrote the following (meaningless) example as a learning expercise (also here: 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: Why isn’t currentValue updated after the call to toCents? (I’m going to guess that it is because currentValue is a literal(?) that it is initialized when CurrencyObject is first executed. If that’s the case, what’s the syntax for also returning the property currentValue?)
Q2: This syntax (with new) var c1 = new CurrencyObject(1.99); does not change the code’s behavior in a way that I can detect, yet I assume there is a difference. What is it?
Q3: When c2 is instantiated, are copies of the functions being created or will c1 and c2 share the same (function) code? (If copies of the functions are being created, what changes do I make to avoid that?)
TIA
BTW: In the event someone is wondering, the symbols in the object literal are quoted to avoid having the Closure-Compiler rename them.
UPDATE:
I branched your fiddle, and added a couple of methods that all instances will in fact share (ie: no new function objects will be created for each instance): the methods that convert the amount into Euro’s or Pounds, for example. I’ve also omitted the
moneyvariable, because it’s simply not necessary. To avoid having to usethisas much as possible, I’ve also assigned the returned object to a variable within the closure scope, so that all methods can reference their parent object via that variable name, rather than having to rely onthis.Shared methods, however, will still have to use
thisoccasionally, because they were declared in a “higher” scope, and don’t have access to thereturnObjectvariable, simply because it doesn’t exist in their scope. Lifting thereturnObjectvariable declaration is no solution in case you were wondering, because then you’ll soon find out that you can’t create more than 1 instance of the currency object.Lastly, I’ve changed the name of the “constructor” to start with a lower case. Technically, your function is not a constructor any longer, and convention is that it therefore can’t start with an upper-case letter… Let me know if anything I explained here, or any of my suggested changes are still unclear to you.
The
currentValueisn’t updated because you changed themoneyvariable’s value by doing:money *= 100;. This statement multiplies themoneyvalue and assigns it to the same variable. Since this is a primitive,currentValuehas its own copy of this value, they’re not linked in any way.Suggestions: use
return money/100;to keep the value ofmoneyconstant. As it now stands calling thetoCentsmethod twice is the same as multiplying the original amount by 10,000. To update/set thecurrentValueon each call to whatever you want it to be, add:this.currentValue = money*100;, which is a little dangerous, or giving your closure access to its own literal by using a named reference (which is safer, but a bit more verbose):There is no reason to use the
newkeyword: the object that is created by this “constructor” is an object literal, it has only 1 prototype (Object.prototype, and no explicit constructor name). Addingnewwill makethispoint to a new object in the function itself, but since you’re not using it, and your function returns another object, the object is never returend.Strictly speaking: some JS engines will create new function objects for each new instance. Some modern objects optimize this, and will in fact only create 1 function object. To be on the safe side, you can wrap another closure around things, to make sure there is only 1 function, regardless of what engine runs your code:
Of course, functions that are created in a scope above the one that has the
moneyoramountvariable won’t have access to that variable, so in that case you’ll have to create new functions… but JS objects are very cheap, so don’t worry about it that much.Again, most engines deal with this rather well.