How to Create js objects and js classes _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces two methods for creating js objects and js classes, which are very simple and recommended to you. The code is very simple, so there is not much nonsense.

The Code is as follows:


// The first definition method
Var person = new Object (); // creates an Object.
Person. name = "tom"; // use the person object to call the name attribute. Its value is tom.
Alert (person. name); // display the name Attribute Value
Person. say = function () {// adds a say function to the person object.
Alert ("person say ");
};
Person. say ();


The Code is as follows:


// Method 2
Var person = {
Name: "tom ",
Say: function (){
Alert ("hello person ");
}
}; // Creates an object.
// Alert (person. name );
// Person. say ();
Person. age = 10;
Alert (person. age );
// Classes defined in js use functions.
Var Person = function (name) {// we are defining a class. It has a constructor with parameters.
This. name = name; // attributes of the class
This. say = function () {// method of the class.
Alert ("say good ");
}
}
Var p = new Person ("fox"); // defines an object of the Person class p
Alert (p. name); // call the name attribute

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.