<script> function parent(age){ this.name = ['mike','jack','smith']; this.age = age; } parent.prototype.run = function () { return this.name + ' are both' + this.age; }; function child(age){ parent.call(this,age);//对象冒充,给超类型传参 } child.prototype = new parent();//原型链继承 var test = new child(21);//写new parent(21)也行 alert(test.run());//mike,jack,smith are both21 </script>
组合式继承的小问题
组合式继承是js最常用的继承模式,但组合继承的超类型在使用过程中会被调用两次;一次是创建子类型的时候,另一次是在子类型构造函数的内部
<script> function parent(name){ this.name = name; this.arr = ['哥哥','妹妹','父母']; } parent.prototype.run = function () { return this.name; }; function child(name,age){ parent.call(this,age);//第二次调用 this.age = age; } child.prototype = new parent();//第一次调用 </script>
以上代码是之前的组合继承,那么寄生组合继承,解决了两次调用的问题。
<script> function f(){} f.prototype = o; return new f(); } function create(parent,test){ var f = obj(parent.prototype);//创建对象 f.constructor = test;//增强对象 } function parent(name){ this.name = name; this.arr = ['brother','sister','parents']; } parent.prototype.run = function () { return this.name; }; function child(name,age){ parent.call(this,name); this.age =age; } inheritprototype(parent,child);//通过这里实现继承 var test = new child('trigkit4',21); test.arr.push('nephew'); alert(test.arr);// alert(test.run());//只共享了方法 var test2 = new child('jack',22); alert(test2.arr);//引用问题解决 </script>
以上就是javascript组合式继承和解决两次调用问题代码详解的详细内容。
