A_Blingbling  

1、原型链继承

非常纯粹的继承关系,实例是子类的实例,也是父类的实例

父类新增原型方法/原型属性,子类都能访问到

 

优点:可以继承构造函数中的属性及方法  也可以继承原型对象中的属性及方法

缺点:不能给父类的构造函数传参数

function Father(){

this.car="劳斯莱斯";

}

function Son(){

this.phone="小米Max";

}

 

Son.prototype=new Father();//通过原型链继承

var s=new Son();

console.log("------:",s.car,s.phone);

 

2、构造函数继承(对象冒充继承);

优点:可以给父类的构造函数传参

缺点:只能继承父类自身的属性和方法,原型对象上的不能继承

function Parent(age){

this.name="张三";

this.age=age;

}

function Child(age){

this.speak=function(){

console.log("听我说说" ,this);

}

Parent.call(this,age);//对象冒充

}

var d=new Child(25);

console.log("d:",d,d.name,d.age);

d.speak();

 

我们看到它解决了原型链继承的通病:

1.避免了引用类型的属性被所有实例共享。

2.可以在 Child 中向 Parent 传参。

3、组合继承  原型继承+冒充继承

function Parent(age){

this.age=age;

this.name=["zhang","wang","li"];

}

Parent.prototype.run=function(){

console.log(this.name+" "+this.age);

}

function Child(age){

this.speak=function(){

console.log("我说说");

}

Parent.call(this,age);//对象冒充

}

Child.prototype=new Parent();//原型链继承

var d=new Child(100);

console.log("d:",d);

d.speak();

d.run();

4、原型式继承

创建的对象的原型=传入的对象

function createObj(o){

 

        function Cat(){} //

     Cat.prototype = o;//-----  创建的对象的原型=传入的对象

      

     return new Cat();

}

 

var animal = {

name:"cat",

friend:["小白","小黑"]

}

 

var a = createObj(animal);

console.log(a);

5、寄生式继承

function person (o) {

var clone = Object.create(o);

clone.sayName = function () {

console.log('hello world');

}

return clone;

}

 

var obj = {

name: '小黑',

friends: ['A', 'B']

}

 

var p1 = person(obj)

console.log(p1)

 

//跟构造函数模式一样,每次创建对象都会创建一遍方法

6、寄生组合式继承

function Parent(name) {

this.name = name;

this.color = ['red', 'blue', 'yellow'];

}

Parent.prototype.getName = function() {

console.log(this.name);

}

function Child(name) {

Parent.call(this, name);  // 子类拥有父类的属性和方法

}

function createObj(o) {

function F() {} // 创建对象

F.prototype = o; // 创建对象的原型  =  obj(传入的对象)

return new F();

}

posted on 2020-12-16 17:48  A_Blingbling  阅读(389)  评论(0编辑  收藏  举报