When defining a JS class, why do you want to set the class's prototype property to the class that it inherits?

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.