JavaScript对象——对象的继承

来源:互联网 发布:各大国家的顶级域名 编辑:程序博客网 时间:2024/05/29 08:57

原型链

每个构造函数都有一个prototype指针指向该构造函数的原型对象,原型对象也有constructor指针指向该构造函数。
如果一个构造函数B的原型对象是构造函数A的实例,B的原型对象的内部属性[[prototype]](__proto__)将指向A的原型对象,如果A的原型对象又是另一个构造函数的实例,如此层层递进,就构成了实例和原型的链条,称为原型链。

继承的方法

1、原型链继承

function SuperType(){    this.property=true;    this.colors=["red","blue","green"];}SuperType.prototype.getSuperValue=function(){    return this.property;}function SubType(){    this.subproperty=false;}SubType.prototype=new SuperType();SubType.prototype.getSubValue=function(){    return this.subproperty;}var instance=new SubType();

①SubType通过原型链继承了SuperType之后,引用类型的属性在原型对象中,不同实例有的属性值相同。
②无法在不影响所有实例属性值的情况下向超类型的构造函数传递参数。

2、借用构造函数继承

function SuperType(){    this.color=["red","blue","green"];}function SubType(){    SuperType.call(this);}

可以传参,如果仅仅是借用构造函数,方法都在构造函数中定义,不存在函数复用。

3、组合继承

使用原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承。

function SuperType(){    this.color=["red","blue","green"];    this.property=true;}SuperType.prototype.getSuperValue=function(){    return this.property;}function SubType(){    SuperType.call(this);    this.subproperty=false;}SubType.prototype.getSubValue=function(){    return this.subproperty;}SubType.prototype=new SuperType();

4、原型式继承

var person={
name:”Alice”,
friends:[“Bob”,”wylla”]
}
var anotherPerson=Object.create(person);

5、寄生式继承

function createAnother(original){
var clone=Object.create(original);
return clone;
}
var person={
name:”Alice”;
frirnds:[“Bob”,”wylla”]
}
var anotherPerson=createAnother(person);

6、组合寄生式继承

function SuperType(){    this.color=["red","blue","green"];    this.property=true;}SuperType.prototype.saySuperValue=function(){    return this.property;}function SubType(){    SuperType.call(this);    this.subproperty=false;}SubType.prototype.saySubValue=function(){    return this.subproperty;}SubType.prototype=Object.create(SuperType.prototype);
0 0
原创粉丝点击