js寄生组合式实现继承

 1 function Person(name, age) {
 2   this.name = name
 3   this.age = age
 4 }
 5 
 6 Person.prototype.eating = function() {
 7   console.log("eating~");
 8 }
 9 
10 Person.prototype.runing = function() {
11   console.log("runing~");
12 }
13 
14 
15 function Student(name, age, sno, score) {
16   // 实现属性继承
17   Person.call( this, name, age)
18   this.sno = sno
19   this.score = score
20 }
21 
22 // 实现方法继承
23 Student.prototype = Object.create(Person.prototype)
24 
25 // 设置constructor
26 Object.defineProperty(Student.prototype, "constructor", {
27   enumerable: false,
28   configurable: true,
29   writable: true,
30   value: Student
31 })
32 
33 Student.prototype.studying = function() {
34   console.log("stying");
35 }
36 
37 
38 var stu = new Student("coderwhy", 18, 110, 99)
39 console.log(stu);
40 console.log(stu.__proto__);
41 stu.eating()
42 stu.runing()
43 stu.studying()

 

posted @ 2021-09-28 10:43  coderchen*  阅读(137)  评论(0)    收藏  举报