JS Create object

Source: Internet
Author: User

<body>
<script>

var o = {
"Na Me": "Kuangjun",
' Age ': 20,
length:155,
Work:function () {
var tmp = "na Me";
Alert (this["na Me"]);

Alert (this[tmp]);
}
};

alert (o.age);
alert (o.length);
O.work ();
How members are accessed

//------------------------
Weak types of programming languages, such as Javascript,ruby

var a = 5;

A = "ADSFA";


Dynamic: The runtime can change, such as the object can dynamically add members

var O2 ={};
O2.name = "Banzhang";
O2.work = function () {
alert (this.name);
}

O2.work ();


Second way to create objects
Habit: When capitalized, this function is not used to invoke,
Instead, it is used to create objects

Stereotype function (Constructor)

function Person (name,age) {

Here this is pointing to the object created by the new person.
This.myname = name;

This.age = age;
This.work = function () {};
}


var p1 = new Person ("Xuewei", 18);
P1.length = 180;//to append a member with JavaScript's dynamic nature
alert (p1.myname);
alert (p1.age);
alert (p1.length);
alert (p1.name);


Adding a static method

PERSON.SP = "static attribute";
PERSON.SP2 = "Static Property 2"
PERSON.SM1 = function () {
Alert (' static method ');
}


alert (PERSON.SP2);

PERSON.SM1 ();

</script>

</body>

JS Create object

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.