JS How to create an object

Source: Internet
Author: User

There are two simple ways to create an empty object: var New Object (); and: var obj = {}; The two methods are semantically identical. The second more convenient method is called the "object literal literal" method. This is also the core syntax in JSON format, generally we prefer the second method. 

object literals can also be used to define an object in an object instance:varobj ={name:"Carrot",    "For": "Max", Details: {color:"Orange", Size:12}} The properties of an object can be accessed by means of a chained (chain) representation: Obj.details.color; //Orangeobj["Details" ["size"];// AThe following example creates an object prototype, a person, and an instance of this prototype, you. functionPerson (name, age) { This. Name =name;  This. Age =Age ;}//defining an Objectvaryou =NewPerson ("You", 24); //we have created a new person, the name is "you"//("You" is the first parameter, 24 is the second parameter:)once created, object properties can be assigned and accessed in two ways: Obj.name= "Simon"varName =obj.name; and: obj["Name"] = "Simon";varName = obj["Name"The two methods are semantically identical. The advantage of the second approach is that the name of the property is treated as a string, which means it can be evaluated at run time, with the disadvantage that such code might not be optimized later by the interpreter. It can also be used to access some of the values of properties that are reserved for the keyword name: obj. for= "Simon";//syntax error because for is a reserved keywordObj["for"] = "Simon";//working properly

JS How to create an object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.