3 ways to create JavaScript objects

Source: Internet
Author: User

3 ways to create JavaScript objects

Method One: Define and create object instances directly

var obj = new Object (); Creating an Object instance

Add attribute Obj.num = 5; Add Property

Obj.fn = function (CIN) {return cin;} Add method

Ways to Access Objects: Objectname.methodname ()

Accessing the properties of an object: Objectname.propertyname

Method Two: Define the object with a function and create an object instance

function Class () {

Add Property

This.val = 1;

Add method

This.fn = function () {

Return ' FN ';

}

}

var obj = new Class (); Creating an Object instance

Ways to Access Objects: Objectname.methodname ()

Accessing the properties of an object: Objectname.propertyname

Method Three: Literals Create object instances directly

Literals creating an object instance is a simplified method.

var obj = {}; Create an empty object

var obj = {

Num: ' 2 ',//This is the Set object property

Fn:function () {

....//This is the Set object method

}

}

Ways to Access Objects: Objectname.methodname ()

Accessing the properties of an object: Objectname.propertyname

---test instance

function www ()
{
var temp = {A: "A", B: "B", C: "C", Fn:function () {
Alert ("FN");
}};

alert (TEMP.B); B

Alert (temp["a"]); A

Temp.fn (); Fn

temp["FN"] (); Fn
}

Through the object name. property name, Object name. Method Name () can be accessed

Object name [method name] () can also be accessed by object name [property name]

3 ways to create JavaScript objects

Related Article

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.