组合继承
-
核心:结合原型继承和call继承的做法。
-
做法:
- 先创建父类和子类构造函数
//父类构造函数 function Person(name,age){ this.name = name; this.age = age; } Person.prototype.sayHi = function(){ console.log("Hi!"); } //子类构造函数 function Student(gender,name,age){ this.gender = gender; } Student.prototype.play = function(){ console.log("Hello World!"); }
-
结合原型继承和call继承
//原型继承 //目的:为了把Person的原型上的内容也能继承下来 Student.prototype = new Person();//注意:这里Person()里面就不要再写参数了 Student.prototype.constructor = Student; //call继承 //目的:为了能把父类构造函数上的内容能直接继承到子类构造函数的实例上去 function Student(gender,name,age){ this.gender = gender; Person.call(this,name,age); } //通过Student构造函数创建一个实例对象 const s1 = new Student("男","Jack",20);
-
结果:console.log(s1);
-
优点:
- 结合了两种继承方式,即能继承到父类构造函数原型上的内容,也能使得父类构造函数上的内容直接出现到实例身上。
-
缺点:
- 里面还存在两个name,age属性用不上,比较占内存。