- 原型链继承
// 原型链的继承 function Person() { this.hobby = { sing: '小星星' } } function Man() { } Man.prototype = new Person() Man.prototype.constructor = Man const man1= new Man() const man2 = new Man() man2.hobby.sing = '两只老虎' console.log(man1.hobby.sing);//两只老虎 console.log(man2.hobby.sing);//两只老虎 // 缺点: // 1、父类属性赋值给子类的原型属性,此时父类属性属于共享属性 // 2、子类实例化时无法向父类传参 //解决办法:构造函数继承
-
构造函数继承
// 构造函数继承 function Person() { this.hobby = { sing: '小星星' } } function Man(arg) { Person.call(this, arg) } const man1 = new Man() const man2 = new Man() man2.hobby.sing='两只老虎' console.log(man1.hobby.sing); console.log(man2.hobby.sing); //缺点:原型链上的方法无法被继承 //解决办法:组合式继承
-
组合式继承
// 组合式继承 function Person() { this.hobby = { sing: '小星星' } } function Man(arg) { Person.call(this, arg) } Man.prototype = new Person() Man.prototype.constructor = Man const man1 = new Man() const man2 = new Man() man2.hobby.sing='两只老虎' console.log(man1.hobby.sing); console.log(man2.hobby.sing); //缺点:会调用两次父类的构造函数 //解决办法:寄生组合式继承
-
寄生组合继承
//寄生组合式继承 function Person() { this.hobby = { sing: '小星星' } } function Man(arg) { Person.call(this, arg) } Man.prototype = Object.creat(Person.prototype) Man.prototype.constructor = Man const man1 = new Man() const man2 = new Man() man2.hobby.sing='两只老虎' console.log(man1.hobby.sing); console.log(man2.hobby.sing);
-
多重继承
// 多重继承 function Person() { this.hobby = { sing: '小星星' } } function Father() { this.sex = '男' } function Child(arg) { Person.call(this, arg) Father.call(this, arg) } Child.prototype = Object.create(Person.prototype) Object.assign(Child.prototype, Father.prototype) Child.prototype.constructor=Child const child1 = new Child() const child2 = new Child() child2.hobby.sing='两只老虎' console.log(child1.hobby.sing); console.log(child2.hobby.sing);
js实现继承的几种方式
于 2022-03-07 17:41:09 首次发布