I have seen the following code in a website... what does this mean?.Can i declare variables in the format variableName : value instead of variableName = value.
if (!window.Node){ var Node = { ELEMENT_NODE : 1, ATTRIBUTE_NODE : 2, TEXT_NODE : 3, CDATA_SECTION_NODE : 4, ENTITY_REFERENCE_NODE : 5, ENTITY_NODE : 6, PROCESSING_INSTRUCTION_NODE : 7, COMMENT_NODE : 8, DOCUMENT_NODE : 9, DOCUMENT_TYPE_NODE : 10, DOCUMENT_FRAGMENT_NODE : 11, NOTATION_NODE : 12 }; }
Those are object properties in an object litteral.
Empty object litteral:
var obj = {};
With properties:
var obj = {
foo: "bar",
test: 123
};
You can then access properties this way:
alert(obj.foo);
Note that this notation only works inside of object litterals. If you want to set a property from outside, also use the dot notation:
obj.foo = "hi";
its an Object Literal.
Follow some tutorials,you'll understand more.. Here's a small tutorial
The line:
if (!window.Node){
Means, if the Node
variable doesn't yet exist, then do the following:
Node
is initialized to an object literal (basically a hash table). For example:
Node['ENTITY_NODE']
is equal to 6.
This can also be expressed as Node.ENTITY_NODE
as well.
The variableName: value
format is what is used to statically declare javascript properties of an object. In your example, Node
is a new object and they are declaring 12 properties for it. You can do that too for property declarations, but property declarations are not exactly the same thing as a variable declaration.
What this code means is: "if window.Node
doesn't already exist, then declare it as an object with these 12 properties".
It can then be accessed like this:
Node.ELEMENT_NODE == 1
The actual purpose of this code is to make sure that these node values are declared once and only once in a given web app so that they can be used by relevant code using meaningful symbol names rather than just comparing to a number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.