Can someone explain what is happening in the code below? I’d expect toString to get called for either both foo and bar, or neither. How is literal object notation different from adding fields to an object after it is created?
function Obj(v) {
this.v = v;
};
Obj.prototype.toString= function() {
window.alert("to string called for " +
this.v);
return this.v.toString();
}
var foo = new Obj('foo');
var bar = new Obj('bar');
// toString is not called here.
var map = {foo : 'blah'};
// toString is called here.
map[bar] = "blah2";
Why do object literals not use toString() while adding to an existing object does use toString()?
The main reason that object literals don’t evaluate the identifier to the left of the colon is so you’re not force to quote all literal names (as you do in JSON).
Bracket notation forces you to quote property names, if you don’t, it will be evaluated as a variable.
The reason
toString()does get called in the second example is becausebarhas to be converted to a string to be used as a property name.In your first example, you’re just creating a literal object (that is the exactly the same as
{"foo" : 'blah'}). So that is never using the variablefooIf you want to create an object using a variable name, you can’t use literal object notation, you have to use
[]which is what forces it to calltoString()Here’s a function to create objects with variable names in one expression.
Clearer Example
The fact that your variable names and values are the same doesn’t help understanding the problem. Let me suggest this code
To do what you need, use my
objfunction