寄生组合式函数继承

关于继承最佳实现就是 寄生组合函数继承 具体看实例

 1 function inheritProtoType(subType, superType) {
 2     subType.prototype = Object.create(superType.prototype)
 3     Object.defineProperty(subType.prototype, "constructor", {
 4         value: subType,
 5         enumberale: true,
 6         congigurale: true
 7     })
 8 }
 9 
10 function Person(mingzi, age, friends) {
11     this.mingzi = mingzi
12     this.age = age
13     this.friends = friends
14 
15 }
16 Person.prototype.eating = function() {
17     console.log(this.mingzi + '在吃饭');
18 }
19 inheritProtoType(Student, Person)
20 
21 function Student(mingzi, age, friends, sno) {
22     Person.call(this, mingzi, age, friends)
23     this.sno = sno
24 }
25 
26 Student.prototype.running = function() {
27     console.log('running');
28 }
29 
30 var stu1 = new Student('tyy', 20, ['tsf'], 2019)
31 var stu2 = new Student('tsf', 22, ['tyy'], 2018)
32 
33 console.log(stu1);
34 console.log(stu2);
35 stu1.eating()
36 stu2.running()

 

 小细节:

1:写了一个inheritProtoType函数来实现,不同父子继承的泛用,更加方便

2:注意把子类原型通过一个新的对象赋值给分类原型时,它只能写在子类构造函数的前面,如果写在之后,子类自己原型上的方法将会无效。

3:图片这里的目的是为了打印出来的对象时子类自己的类型,否则会打印父类原型的constructor的名字

 

posted @ 2022-03-20 14:53  沁霓  阅读(67)  评论(0编辑  收藏  举报