Like in many other programming languages, there are objects in JavaScript.The objects in JavaScript can be compared to object in real life. JavaScript object's is a standalone entity, with its own properties and type . Compare it with a bucket, for example. A bike is an object, with its own properties like it has it's color,design, weight, a material it is made of, etc.JavaScript objects also have its own properties, which define their characteristics of that object.
JavaScript Object Literal
In JavaScript an object literal is a comma-separated list with name-value pairs wrapped in curly braces. It solves the problems which occur at the time of combining code by the use of global variables.
Example object literal is stated below
varnewObject = {
sFind: 'any string value',
numFind: 5,
bFind: true,
};
We can use any data type property value in the object literal it can includes array literals, functions, and nested object literals also. Here is another object literal example with these property types:
var Newclass = {
// an array literal
images: ["new1.gif", "new2.gif", "new3.gif", "new4.gif"],
post: { // nested object literal
x: 80,
y: 700
},
onSwap: function() { // function
// code here
}
};
Object Literal Syntax
The following syntax rules are used to define object literals in javascript:
- A property name from value is separated by colon
- Each name-value pair from the next is separated by comma
- After the last name-value pair there should be no comma.
The syntax rules should not be broken, such as a missing curly brace,or comma or colon or, a JavaScript error will be prompted. The general location of object literal syntax errors can be pointed out by the browser error messages but the complete nature of the error cannot be pointed out .
Why and How We Use Object Literals
Using an object literal in JavaScript will not pollute the global namespace as severely as using many functions declared globally will, and also helps to organise code in a logical fashion.
var obj = {
find : function(element) { /* find code */ },
doThis: function() { /* doThis code */ },
doThat: function() { /* doThat code */ }
}
as compared to
function find(element) { /* find code */ },
function doThis() { /* doSomething code */ },
function doThat() { /* doSomethingElse code */ }
This will create only one property on the global object compared to three. You can then easily use the functions like so
obj.doThis();
0 Comment(s)