一.JS中的继承

ES6之前由于没有extends属性我们必须通过构造函数+原型对象模拟实现继承,被称为组合继承。

ES6之前:借用父构造函数继承属性

 1 //1.父构造函数
 2 function Father(uname ,age){
 3   this.uname = uname;
 4   this.age = age;
 5 }
 6
 7 //子构造函数
 8 function Son(uname ,age ,score){
 9
10   //使用call方法修改this指向子构造函数
11   Father.call(this,uname,age);
12   this.score = score;
13 }
14
15 var son = new Son("小明",14,100);
16 console.log(son);

ES6之前:借用父构造函数+原型对象继承方法

 1 //1.父构造函数
 2 function Father(uname ,age){
 3   this.uname = uname;
 4   this.age = age;
 5 }
 6
 7 Father.prototype.money = function(){
 8
 9 }
10
11 //2.子构造函数
12 function Son(uname ,age ,score){
13
14   //使用call方法修改this指向子构造函数
15   Father.call(this,uname,age);
16   this.score = score;
17 }
18
19 //改变原型对象指向
20 Son.prototype = new Father();
21 //还原构造函数
22 Son.prototype.constructor = Son;
23 //添加原型对象方法
24 Son.prototype.exam = function(){
25
26 }
27
28 var son = new Son("小明",14,100);
29 console.log(son);

 

12-18 14:29