父类衍生子类
1 function Person(name, age){ 2 this.name = name 3 this.age = age 4 } 5 Person.prototype.say = (name) => { 6 console.log('person', name) 7 } 8 function Student(sex){ 9 Person.apply(this, arguments) 10 this.sex = sex 11 } 12 Student.prototype.say = (name) => { 13 console.log('student', name) 14 } 15 // Student.prototype = Person.prototype 16 // Student.prototype.constructor = Student 17 let F= function(){} 18 F.prototype = Person.prototype 19 Student.prototype = new F() 20 Student.prototype.constructor = Student 21 22 let tom = new Student('tom', 20, '男') 23 tom.say('hello') //person:hello
方法缺点:
调用了父类的方法,子类没有重写
方法二:
1 // 父类方法重写 2 var parent = function(name, age) { 3 this.name = name; 4 this.age = age 5 } 6 parent.prototype.showProper = function(){ 7 console.log('name:' + this.name + ';age:' + this.age) 8 } 9 // var child = new parent() 10 var child = function(name,age){ 11 parent.call(this,name,age); 12 } 13 child.prototype = Object.create(parent.prototype); 14 child.prototype.constructor = child 15 child.prototype.showProper = function() { 16 console.log('子元素' + this.name) 17 } 18 var obj = new child('test','2') 19 obj.showProper()
有时间还是再看一下原型链吧
浙公网安备 33010602011771号