Reputation: 148744
Accessing Js object properties :
What is the difference between :
1) Obj.src
vs
2) Obj["src"]
I only know that #1 can't be used with number ( e.g. if the property name is "1")
Is there any other major differences ?
Upvotes: 3
Views: 232
Reputation: 32608
The set of properties that can be accessed with bracket notation is a superset of the properties that can be accessed with dot notation. Anything accessed with the dot must be a valid JavaScript identifier:
a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.
Properties can still be strings that are not identifiers, but require bracket notation for access:
object["I have whitespace"];
object["1startswithanumber"];
object["Punctuation!!??"];
object[""] = "empty string";
// not an exhaustive list
ES5 allows you to use reserved words as properties, x.class = "some string"
, however this is not allowed by ES3, so you should probably use brackets x["class"]
for backwards compatability.
Bracket notation can still be used to access valid identifier properties but dot notation is considered cleaner. Brackets are generally used when you have a variable:
object[input.value]; //Retrieves the property named by the value of the input field
Functions can also be accessed with brackets:
var fn = operation == "tag" ? "getElementsByTagName":"getElementsByClassName";
document[fn](str);
Upvotes: 1
Reputation: 23114
In javascript, every object is an associative array.
I can't think of much more to add besides its one of the better magical features of JavaScript. :)
Upvotes: 1
Reputation: 160963
There is no difference between Obj.src
and Obj["src"]
.
But when the property name is a variable, you could only use the second way to access it.
var name = "src";
Then you need to use Obj[name]
, Obj.name
will try to access the property with the name of name
.
Upvotes: 1
Reputation: 236192
No difference really. Old'ish browser showed some performance differences using either the one or the other notation, but those times are over.
The only important difference is that the bracket notation is your only chance to dynamically access Object properties.
For instance:
var access = 'src';
Obj[ access ];
you can't do that using a dot notation.
Upvotes: 4