1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| function Person(name) { this.name = name }
Person.prototype.getName = function(){ console.log('person fun!') return this.name }
let Student = function(name,age) { Person.call(this,name) this.age = age } let stu = new Student('zs',12) console.log(stu.name) console.log(stu.getName())
let Student = function(){} Student.prototype = new Person() Student.prototype.constructor = Student Student.prototype.stuFun = function(){ console.log('student fun!') } let stu = new Student('123')
console.log(stu.name) console.log(stu.getName()) console.log(stu.stuFun())
3.组合继承,ES6之前常用方案,重复调用两次父类性能损耗 let Student = function(name,age){ Person.call(this,name) this.age = age } Student.prototype = new Person() Student.prototype.constructor = Student Student.prototype.stuFun = function(){ console.log('student fun!') } let stu = new Student('hhh',123) console.log(stu.name) console.log(stu.getName()) console.log(stu.stuFun())
let parent = { name: 'parent', arr: [1,2,3,4], getName: function(){ return this.name } }
let child = Object.create(parent) child.name = 'child' console.log(child.name) console.log(child.arr.pop()) console.log(parent.arr) console.log(parent.name) console.log(child.getName()) console.log(parent.getName())
let parent = { name: 'parent', arr: [1,2,3,4], getName: function(){ return this.name } }
function object(obj){ let child = Object.create(parent) child.childFn = function(){ console.log('add child function!') } return child }
let child = object(parent) child.name = 'child' console.log(child.name) console.log(child.arr.pop()) console.log(parent.arr) console.log(parent.name) console.log(child.getName()) console.log(parent.getName()) console.log(child.childFn());
function Student(name,age){ Person.call(this,name) this.age = age }
Object.setPrototypeOf(Student.prototype,Person.prototype)
let stu = new Student('yyy',12) console.log(stu.name,stu.age) console.log(stu.getName())
class Parent{ constructor(name){ this.name = name; } getName(){ return this.name } }
class Child extends Parent{ constructor(name,age){ super(name) this.age = age } getAge(){ return this.age } }
let child = new Child('hsw',20) console.log(child.name,child.age) console.log(child.getName(),child.getAge())
|