Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Reference type-Object type

Shulou Source: shulou.com Published: 2022-06-01 05:29:42 09月22日 Update

There are two ways to create an instance of Object.

The first is to use the new operator followed by the Object constructor

1 var person = new Object (); 2 person.name = "liao"; 3 person.age = 21

Another way is to use the literal form representation.

1 var person = {2 name: "liao", 3 age: 214}

When using literal syntax, attribute names can also use strings

1 var person = {2 "name": "liao"; 3 "age": 21 position 4 5: true / / numeric attribute names are automatically converted to string 5}

When using literal syntax, if you leave curly braces, you can define objects that contain only default properties and methods

1 var person = {}; 2 person.name = "liao"; 3 person.age = 21

Note: the Object constructor is not called when an object is defined using an object literal

In fact, object literals are the preferred way to pass a large number of optional arguments to a function

1 function displayInfo (args) {2 var output = ""; 3 if (typeof args.name== "string") {4 output + = "Name:" + args.name + "\ n"; 5} 6 if (typeof args.age== "number") {7 output + = "Ages:" + args.age + "\ n" 8} 9 console.log (output); 10} 11 displayInfo ({12 name: "Nicholas", 13 age:2914}); 15 displayInfo ({16 name: "Greg" 17})

In Javascript, you can also use square bracket notation to access the properties of an object (not recommended). Its main advantage is that you can access properties through variables, if the attribute name contains characters that can cause syntax errors

Or the attribute name uses a keyword or reserved word, or you can use square bracket notation

1 var propertyName = "name"; 2 console.log (person [propertyName]); 3 person ["first name"] = "zhi"

Tags: Attributes literals objects functions characters methods representations grammars strings square brackets types advantages keywords parameters variables can be passed followed by instance actual Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info Docker NVidia MariaDB