I saw this code before, but I don’t know what the meaning:
var person1 = {
toLocaleString : function(){
return "Nikolaos";
},
toString : function(){
return "Nicholas";
}
}
var person2 = {
toLocaleString : function(){
return "bum";
},
toString : function(){
return "Greg";
}
}
var people = [person1, person2];
alert(people.toString());
alert(people.toLocaleString());
does the function create an object with the method of toLocaleString and toString??or…??
That code is doing three things:
Objectprototype.Let’s break it down a bit.
1) Object literal notation:
The
{and}in this case denote an object literal. Within an object literal, you can writepropName: propValueto assignpropValueto the property with the namepropNameon the object. This is the same as:You can do multiple properties separated with commas. So for instance:
That creates an object with three properties, two with string values and one with a number value.
Note that the right-hand side are processed just like an assignment, and so can be anything that can appear on the right-hand side of an assignment statement:
The property names can be put in quotes if you like:
…which is handy for specifying properties that have the names of reserved tokens (like “if”, or “return”) or formerly-reserved tokens (like “class”) where it would be a syntax error if they weren’t in quotes.
2) Now let’s look at function expressions:
That’s a function expression. It creates a new function and assigns a reference to it to the variable
f. You can call it by callingf().1 + 2) So putting it together with object literal notation:
(I don’t like anonymous functions, I prefer my functions to have names, but that’s another topic.)
3) And finally: As maerics pointed out, the specific functions that are being used in that code are
toStringandtoLocaleString, both of which are standard functions of JavaScript objects. That means that those will override the standard version and so return the given values whenever the standard function would have been called.