实现继承的方案
假如我们采用这种方式来构造函数对象
1 function Person(name, age, friends) { 2 this.name = name, 3 this.age = age, 4 this.friends = friends 5 this.eating = function() { 6 console.log(this.name + 'eating~~'); 7 } 8 this.running = function() { 9 console.log(this.name + 'running~~'); 10 } 11 12 } 13 14 function Student(name, age, friends, sno) { 15 this.name = name, 16 this.age = age, 17 this.friends = friends 18 this.sno = sno 19 this.eating = function() { 20 console.log(this.name + 'eating~~'); 21 } 22 this.running = function() { 23 console.log(this.name + 'running~~'); 24 } 25 26 } 27 var p1 = new Person('张三', 18, ['lili']) 28 var stu1 = new Student('李四', 20, ['王五'], 2030) 29 p1.eating() 30 stu1.eating()
我们可以看到Person和Student的代码重复很多,这时候可以通过继承来减少代码重复量,继承的特性就是子类可以继承父类
1:通过原型链来实现
1 function Person() { 2 this.mingzi = 'tyy' 3 4 this.eating = function() { 5 console.log(this.name + 'eating~~'); 6 } 7 this.running = function() { 8 console.log(this.name + 'running~~'); 9 } 10 11 } 12 13 function Student() { 14 this.sno = 2019311 15 } 16 var stu = new Student() 17 console.log(stu.mingzi); 18 console.log(stu.sno);

此时stu是获取不到Person里面的mingzi的,如果我们想要Student能够继承Person里面的属性和方法 可以可以把代码修改如下
1 function Person() { 2 this.mingzi = 'tyy' 3 4 } 5 Person.prototype.eating = function() { 6 console.log(this.mingzi + '在吃饭'); 7 } 8 var p = new Person() 9 Student.prototype = p 10 11 function Student() { 12 this.sno = 2019311 13 } 14 var stu = new Student() 15 console.log(stu.mingzi); 16 console.log(stu.sno); 17 stu.eating()
我们加上了8 9行代码就可以实现这是为什么呢,可以画一个内存图

但是这样会有三个弊端
1:不能遍历继承的属性
2:应用变量时对个对象会相互影响
3:不能传参数
1 function Person() { 2 this.mingzi = 'tyy' 3 this.friends = [] 4 5 } 6 Person.prototype.eating = function() { 7 console.log(this.mingzi + '在吃饭'); 8 } 9 var p = new Person() 10 Student.prototype = p 11 12 function Student() { 13 this.sno = 2019311 14 } 15 16 var stu1 = new Student() 17 var stu2 = new Student() 18 stu1.friends.push('lili') 19 20 console.log(stu1.mingzi); 21 console.log(stu1); //第一个弊端 22 console.log(stu1.friends); 23 console.log(stu2.friends); //第二个弊端相互影响

通过另一种方法可以解决上面问题,就是借用构造函数继承
1 function Person(mingzi, age, friends) { 2 this.mingzi = mingzi 3 this.age = age 4 this.friends = friends 5 6 } 7 Person.prototype.eating = function() { 8 console.log(this.mingzi + '在吃饭'); 9 } 10 var p = new Person() 11 Student.prototype = p 12 13 function Student(mingzi, age, friends, sno) { 14 Person.call(this, mingzi, age, friends) 15 this.sno = sno 16 } 17 var stu1 = new Student('tyy', 20, ['tsf'], 2019) 18 var stu2 = new Student('tsf', 22, ['tyy'], 2018) 19 20 console.log(stu1); 21 console.log(stu2);

通过14行代码的方式就能实现
但是这个方式也有弊端
Person被调用了两次,p对象上面会多出不必要的属性

浙公网安备 33010602011771号