JavaScript objects
What are the differences between 开发者_如何学运维these two codes in JavaScript?
var obj = new Object();
obj.X = 10;
obj.Y = 20;
And,
var obj = {X:10, Y:20};
Nothing at all. Just syntax.
You could also use:
var obj = new Object();
obj["X"] = 10;
obj["Y"] = 20;
The second is a shortcut for the first. Functionally they are the same.
Object literal format {}
was introduced with JavaScript 1.2, along with Array literal format []
.
So the more readable variant {X:10, Y:20}
won't work in Netscape 3! (Oh no!)
Nothing really. Well, that's not quite true, but the differences are far too minor to mention.
精彩评论