您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

javascript组合式继承和解决两次调用问题代码详解

2026/3/17 6:24:27发布13次查看
组合式继承是比较常用的一种继承方法,其背后的思路是 使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数复用,又保证每个实例都有它自己的属性。
<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组合式继承和解决两次调用问题代码详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product