What kind of object is this or is it even an object? And how does it work?(JavaScript)
I'm working on a Dashboard widget and I came across a code that looks like this:
var variableName = {
"SomeName":"someValue",
"someName": "another value",
};
That's p开发者_JAVA百科retty much a sum of what it looks like. My question is what is it, how does it work and what can I do with it? An example would be perfect. Thanks in advance!
That's an object literal. It's pretty much just like this:
var variableName = new Object();
variableName.SomeName = "someValue";
variableName.someName = "another value";
This is an example of an object literal.
It creates a normal object with two properties.
While it's called an object literal in JavaScript, it acts more like an enum in most languages.
var messageState = {
new: 0,
read: 1,
deleted: 2
};
With that in place, you have an easy to read way of determining message state:
var message = GetMessage();
if (message.state == messageState.deleted) {
alert('This message is deleted');
}
This is also an easy way to organize functional pieces within your JS file. If you want to only use one JS file for you entire site, which is highly recommended for all kinds of optimization, you can use this instead of writing several different functions:
var Message {
sendMessage: function(msg) {
// method to send msg
},
deleteMessage: function(msg) {
// method to delete msg
}
};
var Vote = {
votePostUp: function(post) {
// method to vote post up
},
votePostDown: function(post) {
// method to vote post down
}
};
And to call:
Message.sendMessage(theMessage);
Vote.votePostUp(myPost);
This is a JavaScript object created with object literal notation.
You can access its properties like this:
variableName["SomeName"];
or
variableName.SomeName;
You can also iterate over the properties of said object (in arbitrary order) with a for...in
loop:
for(var prop in variableName) {
alert(prop + " = " + variableName[prop]);
}
For an excellent guide of working with JavaScript objects, check out this MDN article on working with objects.
What you are looking at is an associative array (a hash map or a dictionary in some languages). Basically it's an array that associates an object with another object, like a word is an associated with its definition in a real dictionary.
It's also JavaScript's main form of objects (they associate function names with function bodies).
精彩评论