进阶的继承

今天来谈谈继承的几种形式吧。

1.原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var Person = function(name){
this.name = name || "noName";
}
Person.prototype.getName = function(){
return `我的名字是: ${this.name}`;
}

var Student = function(name){
this.grade = 1;
this.name = name
}
Student.prototype = new Person();
Student.prototype.getGrade = function(){
return this.grade;
}

var lixiao = new Student("lixiao");

console.log(lixiao.name); //lixiao
console.log(lixiao.getName()); //我的名字是: 李骁
console.log(lixiao.getGrade()); //1
console.log(lixiao instanceof Student); //true
console.log(lixiao instanceof Person); //true
console.log(lixiao.__proto__ === Student.prototype); //true
console.log(lixiao.__proto__.__proto__ === Person.prototype); //true