Prototype and prototype chain, and inheritance

Today, under the review of the prototype and the prototype chain of knowledge, knowledge and records inherited something new to learn.


Knowledge-point platform

  • Prototype and prototype chain
  • es5 and es6 inheritance


What is the prototype chain

The figure is the prototype chain. Global object window has three properties Object, Array, Function. This property has three prototype property, with very many ways in three prototype property. Help us to call when declaring objects, arrays and functions.

Note: In the js function are objects

15907671-98fa173e754c50ca.png
image.png

For example, we declare an empty object a, this empty object has a toStringseries of methods

15907671-3f9f135e3061ac20.png
image.png

15907671-940b1d38ff8ad450.png
image.png

And an array of objects not one by one example.

The process is like?
When we create a object, objects with a __proto__property, this __proto__attribute points to Objectthe prototype. So when a call toStringwhen the method, this method is not a target in itself, so he from __proto__to look for, that is, Objectof prototypewhich there are, so the object will be able to call a toStringmethod.

15907671-278f3155af1dcc0c.png
image.png

How inheritance?

1

function Person(name, sex){
    this.name = name;
    this.sex = sex;
}

Person.prototype.printName = function(){
    console.log(this.name);
};

function Male(name, sex, age){
    Person.call(this, name, sex);
    this.age = age;
}

Male.prototype = Object.create(Person.prototype);

Male.prototype.printAge = function(){
    console.log(this.age);
};

2

function Person(name,sex){
  this.name = name;
  this.sex = sex;
}

Person.prototype.printName = function(){
  console.log(this.name)
}

function Male(name,sex,age){
  Person.call(this,name,sex)
  this.age = age;
}
Male.prototype = new Person()
Male.prototype.printAge = function(){
  console.log(this.age)
}
Male.prototype.constructor = Male

3

class Human {
  constructor(name) {
    this.name = name
  }
  run() {
    console.log('I can run')
  }
}

class Man extends Human {
  constructor(name) {
    super(name)
    this.gender = '男'
  }
  fight(){
    console.log('I can fight')
  }
}

Guess you like

Origin blog.csdn.net/weixin_33919950/article/details/90937544