- 继承方法:
原型链继承
构造函数继承(借助 call)
组合继承
原型式继承
寄生式继承
寄生组合式继承
2.原型链继承
function fun(){
this.obj = 1;
this.foo = function foo(){
console.log(this.obj);
}
}
function fun1(){
this.obj = 2
}
fun1.prototype = new fun();
console.log(new fun1().foo())//2
3.构造函数继承
function fun(){
this.name = 'mike';
this.age = 18;
this.foo = function foo(){
console.log(this.name);
}
}
fun.prototype.getName = function getName(){
console.log(this.name);
}
function fun1(){
fun.call(this);
this.gride = 'man';
}
console.log(new fun().getName(),new fun1().foo(),new fun1().getName())
// mike mike error
4.组合继承
function fun(){
this.name = 'mike';
this.age = 18;
this.foo = function foo(){
console.log(this.name);
}
}
fun.prototype.getName = function getName(){
console.log(this.name);
}
function fun1(){
fun.call(this);
this.gride = 'man';
}
fun1.prototype = new fun();
fun1.constructor = fun1;
console.log(new fun().getName(),new fun1().foo(),new fun1().getName())
//mike mike mike
5.原型式继承
let fun = {
name:'mike',
age: 18,
foo: function foo(){
console.log(this.name)
}
}
fun1 = Object.create(fun);
console.log(fun.foo(),fun1.name)//mike,mike
6.寄生式继承
//寄生式继承在原型式继承基础上进行优化,利用这个浅拷贝的能力再进行增强,添加一些方法
let animal = {
name:'zhangsan',
age:18,
getName: function(){
return this.name
}
}
function clone(obj){
const cloneObj = Object.create(obj);
cloneObj.getAge = function (){
return this.age;
}
return cloneObj;
}
const obj = clone(animal);
console.log(obj.getName(),obj.getAge());//zhangsan 18
7.寄生组合式继承
function clone (parent, child) {
// 这里改用 Object.create 就可以减少组合继承中多进行一次构造的过程
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
}
function Parent6() {
this.name = 'parent6';
this.play = [1, 2, 3];
}
Parent6.prototype.getName = function () {
return this.name;
}
function Child6() {
Parent6.call(this);
this.friends = 'child5';
}
clone(Parent6, Child6);
Child6.prototype.getFriends = function () {
return this.friends;
}
let person6 = new Child6();
console.log(person6); //{friends:"child5",name:"child5",play:[1,2,3],__proto__:Parent6}
console.log(person6.getName()); // parent6
console.log(person6.getFriends()); // child5