//继承,通过原型链实现 function Box() { this.name = 'hg'; }; //被继承的函数叫超类型,其他语言中叫父类,基类. function Desk() { this.age = 100; }; //继承的函数叫子类或者派生类. //通过原型链继承,超类型实例化后的对象,赋值给子类的原型属性 //new Box()会将Box构造里的信息和原型里的信息都交给Desk //Desk的原型得到了Box的构造和原型信息 Desk.prototype = new Box(); var desk = new Desk(); alert(desk.name); alert(desk.age); //继承,通过原型链实现 function Box() { // this.name = 'hg'; }; //被继承的函数叫超类型,其他语言中叫父类,基类. Box.prototype.name = 'jack'; //就近原则,实例没有就找原型 function Desk() { this.age = 100; }; //继承的函数叫子类或者派生类. //通过原型链继承,超类型实例化后的对象,赋值给子类的原型属性 //new Box()会将Box构造里的信息和原型里的信息都交给Desk Desk.prototype = new Box(); var desk = new Desk(); alert(desk instanceof Desk); //true alert(desk instanceof Box); //true 使用对象冒充继承 为了解决引用共享和超类型无法传参的问题,我们采用一种叫借用构造函数的技术,或者成为对象冒充(伪造对象、经典继承)的技术来解决这两种问题。 function Box(age) { this.name = ['hg', 'wj']; this.age = age; }; function Desk(age) { Box.call(this, age); //对象冒充,给超类型传参 }; var desk = new Desk(100); alert(desk.name); //打印成功 缺点:这个无法调用Box声明的原型函数. 组合继承 借用构造函数虽然解决了刚才两种问题,但没有原型,复用则无从谈起。所以,我们需要原型链+借用构造函数的模式,这种模式成为组合继承。 function Box(age) { this.name = ['hg', 'wj']; this.age = age; }; Box.prototype.run = function () { return this.name + this.age + " runing..."; }; function Desk(age) { Box.call(this, age); //对象冒充,给超类型传参 }; Desk.prototype = new Box(); //原型链继承 var desk = new Desk(100); alert(desk.run()); 临时中转函数 function obj(o) { //o表示传入的对象 function F() {}; //F构造一个临时新建的对象,用来存储传入的对象 F.prototype = o; //将o对象实例赋值给F构造的原型对象 return new F(); //返回对象实例 } //F.prototype = o 其实就是var box = new Box(); var box = { name:'lee', age:100, family:[1,2,3], }; var box1 = new obj(box); box1.family.push(4); var box2 = new obj(box); alert(box2.family); //这里共享了引用类型的属性 1,2,3,4 //寄生式继承 = 原型+工厂 寄生组合式集成(解决调用了两次),最终的继承 function obj(o) { function F() {} F.prototype = o; return new F(); } function create(box, desk) { var f = obj(box.prototype); f.constructor = desk; //调整原型指针 desk.prototype = f; } function Box(age) { this.name = ['hg', 'wj']; this.age = age; }; Box.prototype.run = function () { return this.name + this.age + " runing..."; }; function Desk(age) { Box.call(this, age); //对象冒充,给超类型传参 }; create(Box, Desk); //通过这里实现继承 var desk = new Desk(100); alert(desk.run());