js中的继承

it2025-02-01  8

实现原型链有一种基本模式,其代码大致如下:   function A(){      this.property = true; } A.prototype.getAvalue = function(){   return this.property;    }; function B(){      this.property = false; } //继承了A B.prototype = new A(); B.prototype.getBvalue = function(){      return this.property; }; var instance = new B(); console.log(instance.getBvalue());//true;    借用构造函数   function A(){      this.color = ["red","blue"]; }   function B(){      // 继承了A      A.call(this); }  var instance1 = new B(); instance1.color.push("yellow"); console.log(instance1.color);//red,blue,yellow;   var instance2 = new B(); console.log(instance2.color);//red,blue;   1,传递参数 相对于原型链而言,借用构造函数有一个很大的优势,既可以在子类型构造函数中向超类型构造函数传递参数;如下:   function A(){      this.name = name; }   function B(){      //继承了A,同时传递参数      A.call(this,"hello");      // 实例属性;      this.age = 27; } var instance = new B(); console.log(instance.name);//hello console.log(instance.age);//27 2.借用构造函数的问题:如果仅仅是借用构造函数那么也将无法避免构造函数模式存在的问题,方法都在构造函数中定义,因此函数的复用就无从谈起。而且在超类型的原型中定义的方法相对,对子类型而言是不可见的,造成的结果是所有的类型都只能使用构造函数模式。 三.组合继承 组合继承,有时也叫为经典继承,指将原型链和借用构造函数的技术组合到一块,从而发挥二者之长的一种继承模式,思路是:使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。   function A(name){      this.name = name;      this.colors = ["red","blue"]; } A.prototype.sayName = function(){      alert(this.name); }; function B(name,age){      A.call(this,name);      this.age = age; } // 继承方法 B.prototype = new A(); B.prototype.constructor = B; B.prototype.sayAge = function(){      alert(this.age); }; var instance1 = new B("hehe",27); instance1.colors.push("yellow"); instance1.sayName();//hehe instance1.sayAge();//27;   var instance2 = new B("haha",28); console.log(instance2.colors);//red,blue instance1.sayName();//haha instance1.sayAge();//28;   寄生组合式继承:思路,不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型原型的一个副本而已。本质上,就是使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型。如下:   function inheritPrototype(b,a){      var protype = object(a.prototype);//创建对象      prototype.constructor = b;//增强对象      b.prototype = prototype;//指定对象   }   function A(name){          this.name = name;           this.colors =["red","blue"]; } A.prototype.sayName = function (){      console.log(this.name); }; function B(name,age){      A.call(this,name);      this.age = age; }   inheritPrototype(B,A); B.prototype.sayAge = function (){      console.log(this.age); };      

转载于:https://www.cnblogs.com/wtfu/p/6663949.html

最新回复(0)