When defining a JS class, why set the prototype property of the class to the instance object of the class to which it inherits
When writing JavaScript class definitions, it is likely that you have written the following code:
function A() {}
function B() {}
B.prototype = new A()
The above is written so that the instanceof statement works. As an example:
1. Do not rewrite the prototype property of a subclass
b = new B();
b instanceof B //return true
b instanceof A // return false
b instanceof Object //return true
2. Write the prototype property of a subclass
b = new B();
b instanceof B //return true
b instanceof A //return true
b instanceof Object //return true
In addition, the role of prototype can be used to simulate inheritance, so that the property methods we add in the parent class are accessible in subclasses.
But we can use one other way to work around it.
function A(x) {
this.x = x;
this.method1 = functioni () {};
}
function B(x,y) {
A.call(this,x);
this.y = y;
}
b = new B(1, 2)
Then there is absolutely x in B, and X equals 1, but why do we use prototype?
The main purpose is to dynamically add properties and methods to the parent class prototype that can appear in the instance object of the subclass.
And then the example above
A.prototype.z = function () {}
If we do not set b.prototype = new A (), then B does not dynamically Add Method Z.