Http://www.w3school.com.cn/js/js_objects.asp
Creating JavaScript Objects
With JavaScript, you can define and create your own objects.
There are two different ways to create a new object:
- Defining and creating an instance of an object
- Use a function to define an object, and then create a new object instance
Create a direct instance
This example creates a new instance of the object and adds four properties to it:
Instance
Person=new Object ();p erson.firstname= "Bill";p erson.lastname= "Gates";p erson.age=56;person.eyecolor= "Blue";
Try it yourself.
Alternative syntax (using object literals):
Instance
Person={firstname: "John", LastName: "Doe", Age:50,eyecolor: "Blue"};
Try it yourself.
Using the Object Builder
This example uses a function to construct an object:
Instance
function Person (firstname,lastname,age,eyecolor) {this.firstname=firstname;this.lastname=lastname;this.age=age; This.eyecolor=eyecolor;}
Try it yourself.
Creating an instance of a JavaScript object
Once you have the object constructor, you can create a new object instance, just like this:
var myfather=new person ("Bill", "Gates", "page", "Blue"), var mymother=new person ("Steve", "Jobs", "green");
Add attributes to JavaScript objects
You can add a new property to an existing object by assigning a value to the object:
Suppose Personobj already exists-you can add these new properties to it: FirstName, LastName, Age, and Eyecolor:
Person.firstname= "Bill";p erson.lastname= "Gates";p erson.age=56;person.eyecolor= "Blue"; x=person.firstname;
After the above code is executed, the value of X will be:
Bill
Add a method to a JavaScript object
method is simply a function attached to an object.
Methods for defining objects inside the constructor function:
function Person (firstname,lastname,age,eyecolor) {this.firstname=firstname;this.lastname=lastname;this.age=age; This.eyecolor=eyecolor;this.changename=changename;function ChangeName (name) {this.lastname=name;}}
The value of the ChangeName () function name is assigned to the LastName property of the person.
Now you can try it:
Mymother.changename ("Ballmer");
Try it yourself.
JavaScript class
JavaScript is an object-oriented language, but JavaScript does not use classes.
In JavaScript, classes are not created and objects are not created through classes (as in other object-oriented languages).
JavaScript is based on prototype, not class-based.
Creating JavaScript Objects