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