一、原型链继承 在原型链继承方面,JavaScript与java、c#等语言类似,仅允许单父类继承。prototype继承的基本方式如下: 复制代码 代码如下: function Parent(){} function Child(){} Child.prototype = new Parent();
通过对象Child的prototype属性指向父对象Parent的实例,使Child对象实例能通过原型链访问到父对象构造所定义的属性、方法等。 构造通过原型链链接了父级对象,是否就意味着完成了对象的继承了呢?答案是否定的。如: 复制代码 代码如下: function Parent(){} function Child(){} Child.prototype = new Parent(); var child = new Child(); alert(child.constructor);//function Parent(){} alert(child instanceof Child);//true
尽管child依然可以作为Child的实例使用,但此时已经丢失了实例child原有的对象构造信息。弥补该缺陷的方法如下: 复制代码 代码如下: function Parent(){} function Child(){} Child.prototype = new Parent(); Child.prototype.constructor = Child; var child = new Child(); alert(child.constructor);//function Parent(){} alert(child instanceof Child);//true
三、对象实例间的继承 JavaScript对象的多态性,允许实例动态地添加属性、方法。该特性造就了JavaScript中的另一种继承手法——对象实例间的继承。如: 复制代码 代码如下: var Person = {name:"nathena",age:"26"}; var nathena = {sex:"male"}; (function inlineExtends(so,po) { for (var i in po) { if (so[i])//如果so也具有这个成员 continue; so[i] = po[i]; } })(nathena,Person); alert(nathena.name);//返回nathana