Introduction to JavaScript type Object

  • 2020-05-24 05:13:56
  • OfStack

There are two ways to create an Object instance. The first is to use the new operator followed by the Object constructor, as follows:


var person = new Object();
person.name = "zxj";
person.age = 25;

Another way is to use object literal notation. Object literals are a shorthand form of object definition to simplify the process of creating objects with a large number of properties. The code is as follows:


 // Object literal
 var person = {
 name: "zxj",
 age: 25
 }

The Object constructor is not actually called when defining an object by its literal.

1 generally, object properties are accessed using dot notation, but you can also access object properties using square bracket notation in JavaScript. When using the square bracket syntax, the properties to be accessed should be placed inside the square brackets as a string, as follows:


alert(person["name"]) //zxj
alert(person.name) //zxj

The two functions are no different, but the main advantage of the square bracket syntax is that you can access properties through variables:


var propertyName="name";
alert(person[propertyName]); //zxj

You can also use square brackets if the property name contains characters that cause syntax errors, or if the property name USES keywords or reserved words, such as:


person['first name'] = "zxj";

In general, dot notation is recommended unless you must use square brackets notation.


Related articles: