Using Object Syntax

To use objects in JavaScript effectively, you need to have an understanding of their structure and syntax. An object is really just a container to group together multiple values and, in some instances, functions. The values of an object are called properties and the values of functions are called methods.

To use a JavaScript object, you must first create an instance of the object. You create object instances by using the new keyword with the object constructor name. For example, to create a Number object, you could use the following line of code:

var x = new Number("5");

Object syntax is very straightforward: You use the object name and then a dot and then the property or method name. For example, the following lines of code get and set the name property of an object named myObj:

var s = myObj.name;
myObj.name = "New Name";

You can also get and set object methods of an object in the same manner. For example, the following lines of code call the getName() method and then change the method function on an object named myObj:

var name = myObj.getName();
myObj.getName = function() { return this.name; };

You can also create objects and assign variables and functions directly by using {} syntax. For example, the following code defines a new object and assigns values and a method function:

var obj = {
    name: "My Object",
    value: 7,
    getValue: function() { return this.name; };
};

You can also access members of a JavaScript object by using the object[propertyName] syntax. This is useful when you are using dynamic property names and when the property name must include characters that JavaScript does not support. For example, the following examples access the "User Name" and "Other Name" properties of an object name myObj:

var propName = "User Name";
var val1 = myObj[propName];
var val2 = myObj["Other Name"];

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.46.18