Detailed usage of prototype in Javascript

  • 2021-06-29 09:34:34
  • OfStack

Let's start with 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();

This code, although an Machine object is created, passes through machine.showme = showme;This makes the showme function a method of the Machine object machine.

However, there is nothing to do with the above two functions (one is the object's constructor and one is the common method). Such code is not so "elegant", so there is prototype.


// machine 
function Machine(ecode, horsepower) {
  this.ecode = ecode;
  this.horsepower = horsepower;
}
// Pay special attention to this 1 Sentences, Machine.prototype Is 1 It is initialized the next time. 
// When called Machine As a constructor, engine The value of 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 an showme method.

But pay special attention to:

prototype only faces instances, not class objects. (In js, the class itself is an object), so Machine.showme();Errors will be reported because the Machine object does not have an showme method.

So how do we use the showme method?A new Machine instance must be created, and only an Machine instance will have this method.


var machine = new Machine("code1", 15);
machine.name = "machine1";
machine.showme(); // output machine1 code1 15 . 

With prototype, it's easier to implement inheritance relationships.For example, if I write an Car class now, I need to inherit the current Machine class, just write the following code:


// A car 
function Car(name, ecode, horsepower) {
  this.name = name;
  // Call the parent class's constructor so that Car Objects are ecode , horsepower attribute 
  Machine.call(this, ecode, horsepower);
}
//Car Prototype pointing Machine To Car Objects have Machine Any properties and methods of the prototype, such as showme
Car.prototype = new Machine();

How to call the parent constructor here and get the prototype of the parent class is well documented and will not be overlooked.

Then we can create a new object test 1:


// Newly build 1 Classes Car Object. 
var xiali = new Car("xiali", "aaa", 15);
alert(xiali.engine);
xiali.showme();

Above, it is the basic application of prototype, but it is also the main application of prototype.

Master the use of prototype, in the future, will have a deeper understanding of the construction and inheritance of objects.


Related articles: