时间:2021-07-01 10:21:17 帮助过:3人阅读
<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组合式继承和解决两次调用问题代码详解的详细内容,更多请关注Gxl网其它相关文章!