- 使用for-in实现继承
- 通过call或者apply实现伪造继承
- 通过原型对象实现继承
- 通过原型和call的组合实现继承
//1、使用for-in实现继承 function Parent() { this.name = 'parent'; this.color = ['red', 'green']; } Parent.prototype.showName = function () { return `姓名:${this.name}`; } function Child(age) { this.age = age ; let p = new Parent(); for(let key in p) { this[key] = p[key]; } } Child.prototype.getAge = function () { return `芳龄:${this.age}`; } let child = new Child(18); child.name = 'Child'; console.log(child); console.log(child.getAge()); console.log(child.showName()); //2、通过call或者apply实现伪造继承 function Parent2(name, email) { this.name = name; this.email = email; this.sayHi = function () { return 'hhh'; } } // 使用call或apply不可以实现原型对象上面的属性和方法的继承 Parent2.prototype.say = function () { return 'hello'; } function Child1(name, age, email) { this.age = age; Parent2.call(this, name, email); } function Child2(name, email) { this.age = 22; // arguments是函数内部获取实参的集合 Parent2.apply(this,arguments); } let child1 = new Child1('zs',33,'[email protected]'); let child2 = new Child2('zs','[email protected]'); console.log(child1); //3、通过原型对象实现继承 function Parent3() { this.name = 'parent'; this.color = ['red', 'green']; } Parent3.prototype.showName = function () { return `parent:my name is ${this.name}`; } function Child3(age) { this.age = age ; } Child3.prototype = new Parent3(); Child3.prototype.getAge = function () { return `child:my age is ${this.age}`; } let child3 = new Child3(12); console.log(child3.showName()); console.log(child3.getAge()); //4、通过原型和call的组合实现继承 function Parent4(name, color) { this.name = name; this.color = color; } Parent4.prototype.showName = function () { return `parent4: ${this.name}`; } function Child4(age, name, color) { this.age = age; Parent4.call(this,name,color); } Child4.prototype = new Parent4('parent4',['yellow']); Child4.prototype.getAge = function () { return `child4:my age is ${this.age}`; } let child4 = new Child4(25,'k',['k_color']); console.log(child4.name); console.log(child4.getAge()); child4.color.push('k1_color'); console.log(child4.color); let child5 = new Child4(26,'k5',['k5_color']); child5.color.push('k55_color'); console.log(child4.color); console.log(child5.color);