Object inheritance

  • An important aspect of object-oriented programming is object inheritance. By inheriting from B, object A can directly own all properties and methods of object B.

1. Disadvantages of constructors

  • JavaScript generates new objects through constructors, so constructors can be seen as templates for objects. The properties and methods of the instance object can be defined inside the constructor.
function User(name,age) {
	this.name = name;	
	this.age = age;
}

var user = new User('Joe'.19)
console.log(user.name + '=' + user.age) // 张三 = 19
Copy the code
  • In the above code, the User function is a constructor that internally defines the name and age attributes, which are generated by all instance objects (User in this example), i.e., they are defined on the instance object.

  • Defining attributes for instance objects through constructors, while convenient, has one drawback. Multiple instances of the same constructor cannot share attributes, resulting in a waste of system resources.

function User(name,age) {
    this.name = name;
    this.age = age;
    this.sayName  = function() {
        console.log(Object oriented)}}var user1 = new User('Joe'.19)
var user2 = new User('Joe'.19)
console.log(user1.name + '=' + user1.age) // 张三 = 19
console.log(user1.sayName == user2.sayName) // false
Copy the code
  • In the code above,user1anduser2Are two instances of the same constructor, which both havesayNameMethods. Due to themeowThe method is generated on each instance object, so the two instances are generated twice. That is, for every new instance created, a new instance will be createdsayNameMethods. This is both unnecessary and a waste of system resources because allmeowMethods are all the same behavior and should be completely shared.
  • The solution to this problem is JavaScript prototype objects.

2. Prototype properties

  • The JavaScript inheritance mechanism is designed with the idea that all properties and methods of the prototype object can be shared by the instance object. That is, if properties and methods are defined on the stereotype, then all instance objects can be shared, saving memory and showing the relationship between instance objects.
function f() {}
typeof f.prototype // "object"
Copy the code
  • In the case of constructors, this property automatically becomes the prototype of the instance object when the instance is generated.
 function Cat(name) {
     this.name = name
 }
Cat.prototype.price = 1200
var cat = new Cat('corgi')
var cat2 = new Cat('they')
console.log(cat.name, "," + cat.price) / / corgi, 1200
console.log(cat2.name, "," + cat2.price) / / shiba inu, 1200
Copy the code
  • In the above code, the prototype property of the constructor Cat is the prototype object of the instance objects Cat and cat1. A price attribute is added to the prototype object, and as a result, the instance objects share this attribute.

  • The purpose of a stereotype object is to define properties and methods shared by all instance objects. This is why it is called a prototype object, and instance objects can be considered children of the prototype object.

Cat.prototype.getName = function() {
	console.log(this.name)
}
var cat3 = new Cat('they')
cat3.getName() / / the shiba inu
Copy the code
  • In the code above,Cat.prototypeObject defined abovegetNameMethod, this method will be available at allCatCalled on the instance object.

3. Prototype chain

  • All objects have their own prototype objects, and any object can act as a prototype for other objects. Since the prototype object is also an object, it also has its own prototype, object to prototype, and prototype to prototype, thus forming a prototype chain

If you layer up, all Object prototypes can eventually be traced back to Object.prototype, the Prototype property of the Object constructor. That is, all objects inherit the properties of Object.prototype. This is why all objects have valueOf and toString methods, because these are inherited from Object.prototype.

Does the object. prototype Object have a prototype? Object. Prototype is null. Null has no properties, no methods, and no prototype of its own. Thus, the end of the prototype chain is NULL.

Object.getPrototypeOf(Object.prototype)
// null
Copy the code

Prototype is null. Null has no attributes, so the prototype chain ends there.

4. Constructor attribute

  • prototypeObject has oneconstructorProperty, the default point toprototypeThe constructor of the object.
function P() {}
P.prototype.constructor === P // true
Copy the code

In the above code, p is an instance object of the constructor p, but p itself has no constructor property, which actually reads the p.prototype. constructor property above the prototype chain.

The constructor property lets you know which constructor generated an instance object.

function F() {};
var f = new F();

f.constructor === F // true
f.constructor === RegExp // false
Copy the code

On the other hand, with the constructor attribute, you can create another instance from one instance object.

function Constr() {}
var x = new Constr();

var y = new x.constructor();
y instanceof Constr // true
Copy the code

5. The instanceof operator

  • instanceofThe operator returns a Boolean value indicating whether the object is an instance of a constructor.
var v = new Vehicle();
v instanceof Vehicle // true
Copy the code

Constructor inheritance

Here is a Shape constructor.

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function (x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};
Copy the code

We need to have the Rectangle constructor inherit Shape.

// The subclass inherits the instance of the parent class
function Rectangle() {
  Shape.call(this); // Call the parent constructor
}
// Another way to write it
function Rectangle() {
  this.base = Shape;
  this.base();
}

// Step 2, the subclass inherits the prototype of the parent class
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Copy the code

When written this way, the instanceof operator returns true for both subclass and superclass constructors.

var rect = new Rectangle();

rect instanceof Rectangle  // true
rect instanceof Shape  // true
Copy the code

In the code above, a subclass inherits its parent class. Sometimes only inheritance from a single method is required, which can be written as follows.

ClassB.prototype.print = function() {
  ClassA.prototype.print.call(this);
  // ...
}
Copy the code

In the code above, the print method of subclass B calls the print method of its parent class A before deploying its own code. This is equivalent to inheriting the print method of the superclass A.