js编程-继承

78 阅读1分钟

1、原型继承 : 子类原型指向父类实例 (查找/指向)

例:

function Parent() {};

function Child() {};

Child.prototype = new Parent;

Child.prototype.constructor = Child;

child.prototype.xxx = function xxxx() {};

特点: 1)父类中私有和公有的属性和方法,都变成子类实例公有的;

2)和其他语言不同的是:原型继承并不会把父类的属性和方法“拷贝”给子类,而是让子类实例基于__proto__原型链找到自己定义的属性和方法,指向/查找方式的。

2、CALL继承 : 在子类构造函数中,把父类构造函数当作普通函数执行(没有父类实例,父类原型上的公有属性与子类没有关系)(拷贝式继承)

例:

function Parent() { this.x = 10; };

Parent.prototype.xxx = function xxx() {};

function Child() {

Parent.call(this); ---> this.x = 10 相当于强制给子类实例设置一个私有属性,相当于子类的实例继承了父类的属性,也变成了子类的私有属性

this.y = xxxx;

}

Child.prototype.xxx = function xxx() {}

3、寄生组合式继承 : CALL继承+ 另类原型继承(子类原型 指向父类原型)

例:

function Parent() { this.x = 10; };

Parent.prototype.xxx = function xxx() {};

function Child() {

Parent.call(this)

this.y = xxxx;

}

Child.prototype = Object.create(Parent.prototype);

Child.prototype.constructor = Child;

Child.prototype.xxx = function xxx() {};