Let's first 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 piece of code, after creating a Machine object, the showme function becomes the machine object machine method through machine.showme = showme;
However, it depends on the above two functions (one is the object constructor and the other is the ordinary method) that have nothing to do with each other. Such code is not so "elegant", so there is a prototype.
//Machine function Machine(ecode, horsepower) { this.ecode = ecode; this.horsepower = horsepower;}// Pay special attention to this sentence. Machine.prototype is initialized when it is initialized for the first time. //When calling Machine as the constructor, the value of engine will not change again Machine.prototype.engine = this.ecode + " " + this.horsepower;Machine.prototype.showme = function () { alert(this.name + " " + this.ecode + " " + this.horsepower); }Using the above code, all Machine objects have a showme method.
But pay special attention to:
prototype is only facing 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 a showme method.
So, how do we use the showme method? A new Machine instance must be created, and only the Machine instance will have this method.
var machine = new Machine("code1", 15);machine.name = "machine1";machine.showme(); //Output machine1 code1 15.With prototype, it is easier for us to implement inheritance relationships. For example, if I write a Car class now, I need to inherit the current Machine class, and I just need to write the following code:
//Car function Car(name, ecode, horsepower) { this.name = name; //Calculating the constructor of the parent class, so that the Car object has ecode and horsepower attributes Machine.call(this, ecode, horsepower);}//Car's prototype points to the Machine, so that the Car object has any properties and methods of the Machine prototype, such as showmeCar.prototype = new Machine();The annotation is very clear here, so I won't go into details.
Then, we can create a new object to test it:
//Create a new object of class Car. 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 most important application of prototype.
The use of prototype you master will have a deeper understanding of the construction and inheritance of objects in the future.
To view more JavaScript syntax, you can follow: "JavaScript Reference Tutorial" and "JavaScript Code Style Guide". I also hope that everyone will support Wulin.com more.