Let's take a look at the following code:
function Machine(ecode, horsepower) {
this.ecode = ecode;
this.horsepower = horsepower;
}
function showme() {
alert(this.name + " " + this.ecode + " " + this.horsepower);
}
var machine = new Machine("code1", 15);
machine.name = "machine1";
machine.showme = showme;
machine.showme();
In this Code, although a Machine object is created, the showme function becomes the machine object Machine method through machine. showme = showme.
However, the above two functions (one is the object constructor and the other is a common method) have no relationship. Such code is not so "elegant". Therefore, the prototype is available.
// Machine
Function Machine (ecode, horsepower ){
This. ecode = ecode;
This. horsepower = horsepower;
}
// Note that Machine. prototype is initialized during the first initialization,
// When the Machine is called as the constructor, the engine value will not change.
Machine. prototype. engine = this. ecode + "" + this. horsepower;
Machine. prototype. showme = function () {alert (this. name + "" + this. ecode + "" + this. horsepower );}
With the above Code, all Machine objects have the showme method.
Note:
Prototype only faces instances, not class objects. (In js, the class itself is an object) So Machine. showme (); will report an error because the Machine object does not have the showme method.
So how can we use the showme method? You must create a new Machine instance. This method is available only for the Machine instance.
Var machine = new Machine ("code1", 15 );
Machine. name = "machine1 ";
Machine. showme (); // output machine1 code1 15.
With prototype, we can implement inheritance relationships more easily. For example, if I want to write a Car class that inherits the current Machine class, I only need to write the following code:
// Car
Function Car (name, ecode, horsepower ){
This. name = name;
// Call the constructor of the parent class so that the Car object has the ecode and horsepower attributes.
Machine. call (this, ecode, horsepower );
}
// The Car prototype points to the Machine so that the Car object has any attributes and methods of the Machine prototype, such as showme
Car. prototype = new Machine ();
How to call the parent constructor and obtain the prototype of the parent class is not described here.
Then, we can create a new object for testing:
// Create a Car-like object.
Var xiali = new Car ("xiali", "aaa", 15 );
Alert (xiali. engine );
Xiali. showme ();
The above is the basic application of prototype, but it is also the main application of prototype.
In the future, we will have a deeper understanding of Object Construction and inheritance.