"use strict"; var p = console.log; //1原型链继承 //单纯地将子构造函数的原型指向父构造函数的实例 function SuperType(){ } function SubType(){ } SubType.prototype = new SuperType(); //修正构造函数 SubType.constructor = SubType; //2借用构造函数(伪造对象或经典继承) //优点:可以传递参数 //缺点:超类中的引用类型值(主要是函数)无法复用 /* 使用this为实例产生property,property 属于实例 */ function SuperType(){ this.property = "zackbee"; } function SubType(){ //继承SuperType SuperType.call(this); } var instance = new SubType(); p(instance instanceof SubType);//true p(instance instanceof SuperType);//false p(instance.hasOwnProperty("property"));//true //3组合继承(伪经典继承) //优点:保证了instanceof返回值正确 //缺点:我觉得好用 function SuperType(name){ this.name = name; this.colors = ["red", "green"]; } SuperType.prototype.sayName = function(){ p(this.name); }; function SubType(name, age){ SuperType.call(this, name); this.age = age; } SubType.prototype = new SuperType(); //修正constructor SubType.prototype.constructor = SubType; //4原型式继承(道格拉斯推广) //优点:简洁,不需要构造函数就能复制出对象 //缺点:两个instance复制同一个对象时,对对象中的引用 //类型的值进行操作会相互影响 //instance无法返回正确值 function object(o){ function F(){} F.prototype = o; return new F(); } //上面即函数Object.create()的实现原理 var person = { //一个对象 name:"zackbee", friends:["zack", "bee"], method:function(){ } }; //5寄生式继承 //优点:简洁快速地复制出一个对象 //缺点:仅限于复制一个对象,不然多个对象的引用类型 //会操作会互相影响 function createAnother(original){ var clone = Object(original);//调用Object创建一个新对象 clone.sayHi =function(){ p("dashazi"); }; return clone; } var person = { name:"zackbee", friends:["zack", "bee"] }; var instance = createAnother(person); var anotherPerson = createAnother(person); instance.friends.push("shazi"); var anotherPerson1 = object(person); anotherPerson1.name = "zack"; var anotherPerson2 = object(person); anotherPerson2.name = "bee"; anotherPerson1.friends.push("geek"); p(anotherPerson2.friends);//[ 'zack', 'bee', 'geek' ] //寄生组合式继承 //优点:据说是最优雅的继承方法,没有感觉出来 //使用超类型的副本作为原型prototype构造出 //中间过程的var prototype,使用原型进行一系列继承操作 //似乎还不错 function SuperType(name){ this.name = name; this.color = ["red", "blue", "green"]; } SuperType.prototype.sayName = function(){ p(this.name); }; function SubType(name, age){ SuperType.call(this, name); this.age = age; } function inheritPrototype(SubType, SuperType){ var prototype = Object(SuperType.prototype); prototype.constructor = SubType; SubType.prototype = prototype; } inheritPrototype(SubType, SuperType); SubType.prototype.sayAge = function(){ p(this.age); };
发现xx式继承都是道格拉斯推广的,而且都是用了简单地复制副本,如果想要像其他语言类的实现方法,我觉得组合
继承挺好用的(es6中有class的概念,然而是语法糖)