js的六种继承(上)
function Father(name, age) {
this.name = name;
this.age = age;
this.sayHello = function () {
console.log("hello son")
}
}
Father.prototype.sex = 'man';
Father.prototype.sayHello2 = function () {
console.log("hello my son")
}
原型链式继承
function Son() {
}
Son.prototype = new Father();
function Son1() {
}
Son1.prototype = new Father();
console.log("Son==>", new Son());
console.log("Son.sex==>", new Son().sex);
new Son().sayHello();
new Son().sayHello2();
console.log("Son1==>", new Son1());
console.log("Son1.sex==>", new Son1().sex);
new Son1().sayHello();
new Son1().sayHello2();
console.log("============华丽分割线==========")
Son1.sex = "woman";
console.log("Son1.sex==>", new Son1().sex);
console.log("Son.sex==>", new Son().sex);

原型链式继承总结
简单得说,原型链式继承就是把父类的实例对象放在子类的原型上
优点:能继承父类构造函数内部的方法,父类构造函数原型上的方法和属性
缺点:1.不能传参,缺少灵活性
2.继承的父类构造函数原型上的属性是共享的,一旦修改,一改全改
构造函数式继承
function Son(name, age) {
Father.call(this, name, age)
}
function Son1(name, age) {
Father.call(this, name, age);
this.age = age;
}
const son = new Son('小明', 18);
const son1 = new Son1('小红', 22)
console.log("son==>", son);
console.log("son.name==>", son.name)
console.log("son.age==>", son.age)
console.log("son.sex==>", son.sex);
son.sayHello();
console.log("son1==>", son1);
console.log("son1.name==>", son1.name)
console.log("son1.age==>", son1.age)
console.log("son1.sex==>", son1.sex);
son1.sayHello();

构造函数式继承总结
构造函数式继承关键在于在子类内部,使用call或者apply引入父类构造函数
优点:1.能传递参数,继承更加灵活,
2.由于每一个都是一个新实例,属性不再是共享的
缺点:1.父类构造函数上的属性和方法都不能继承
组合式继承
通过观察可以发现,原型链式继承和构造函数式继承的优缺点是刚好相反的。
有人想可不可以两者一起综合起来,这就是组合式继承
function Son(name, age) {
Father.call(this, name, age)
}
Son.prototype = new Father();
function Son1(name, age) {
Father.call(this, name, age);
this.age = age;
}
Son1.prototype = new Father();
const son = new Son('小明', 18);
const son1 = new Son1('小红', 22)
console.log("son==>", son);
console.log("son.name==>", son.name)
console.log("son.age==>", son.age)
console.log("son.sex==>", son.sex);
son.sayHello();
son.sayHello2();
console.log("son1==>", son1);
console.log("son1.name==>", son1.name)
console.log("son1.age==>", son1.age)
console.log("son1.sex==>", son1.sex);
son1.sayHello();
son1.sayHello2();
son.sex = 'women'
console.log("son.sex==>", son.sex);
console.log("son1.sex==>", son1.sex);

组合式继承总结
优点:可继承父类原型上属性和方法,可传参
缺点:1.每一次new一个实例的时候,相对于父类被new了两次,会耗内存
凡是有关原型链式继承的,都会出来原型链紊乱的问题
console.log(Son.prototype.constructor)

Son.prototype = new Father();
Son.prototype.constructor = Son;