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
For example, we declare an empty object a, this empty object has a toString
series of methods
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 Object
the prototype
. So when a call toString
when the method, this method is not a target in itself, so he from __proto__
to look for, that is, Object
of prototype
which there are, so the object will be able to call a toString
method.
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')
}
}