Combined inheritance is a commonly used inheritance method. The idea behind it is to use the prototype chain to inherit prototype properties and methods, and to borrow constructors to achieve inheritance of instance properties. In this way, function reuse is achieved by defining methods on the prototype, and each instance is guaranteed to have its own attributes.
<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>
Small problems with combined inheritance
Combined inheritance is the most commonly used inheritance pattern in js, but the supertype of combined inheritance will be called twice during use; once to create a child type, and the other time is inside the subtype constructor
<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>
The above code is the previous combined inheritance, so parasitic combined inheritance solves the problem of two calls.
<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>
The above is the detailed content of Detailed code explanation of javascript combined inheritance and solving the problem of two calls. For more information, please follow other related articles on the PHP Chinese website!