js中的繼承無論是在面試還是在實際應用中都是一個高頻的知識點,總結梳理下。
方法1.通過構造函數(shù)實現(xiàn)繼承
/*
借助構造函數(shù)實現(xiàn)繼承
*/
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function () {
console.log(this.name);
}
function Man(name) {
Person.call(this,name);
}
var liming = new Man('liming');
console.log(liming.sayName())
通過構造函數(shù)繼承的這種方法的缺點就是不能繼承父類原型上的方法。
方法2.通過原型鏈實現(xiàn)繼承
/*
借助原型鏈實現(xiàn)繼承
*/
function Perant() {
this.name = 'parent';
this.play = [1,2,3];
}
function Child() {
this.type = 'child2';
}
Child.prototype = new Perant();
var s1 = new Child();
var s2 = new Child();
console.log(s1.play,s2.play);//[1,2,3] [1,2,3]
s1.play.push(4);
//s1的play添加新元素后,s2中的play也添加了新元素
console.log(s1.play, s2.play);//[1,2,3,4] [1,2,3,4]
這種方法的缺點就是每個實例都引用了父類的對象,所以一個實例修改繼承對象的屬性送浊,所有的實例引用的父類屬性就也受到了修改。
方法3.組合繼承
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function () {
return this.name
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructer = Child;
var p1 = new Child('limming');
console.log(p1.sayName());
組合繼承的這種方式很好的解決構造函數(shù)繼承和原型鏈繼承的方法的兩種缺點丘跌,組合繼承中通常將公用的方法放在原型鏈上袭景,私有的屬性放在構造函數(shù)中。
組合繼承中需要注意的是不忘將子類的原型上的contructor重新指向子類
Child.prototype.constructer = Child;
Object.create
方法會使用指定的原型對象及其屬性去創(chuàng)建一個新的對象闭树。這API是IE9中才支持耸棒,兼容的寫法如下
funciton F(){}
F.prototype = Parent.protoype;
Child.prototype = new F();
方法4.ES6中的繼承
class Parent {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
console.log(this.name + ':我是社會主義接班人');
}
}
class Child extends Parent {
constructor(name, age, sex) {
super(name, age);
this.sex = sex;
}
printSex() {
console.log(this.sex);
}
}
var ruoyu = new Child('小明', '27', '男');
ruoyu.say();
ruoyu.printSex();