类的继承在几年前是重点内容,有n种继承方式各有优劣,es6普及后越来越不重要,那么多种写法有点『回字有四样写法』的意思,如果还想深入理解的去看红宝书即可,我们目前只实现一种最理想的继承方式。
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
| function Parent(name) { this.parent = name } Parent.prototype.say = function() { console.log(`${this.parent}: 你打篮球的样子像kunkun`) } function Child(name, parent) { Parent.call(this, parent) this.child = name }
Child.prototype = Object.create(Parent.prototype); Child.prototype.say = function() { console.log(`${this.parent}好,我是练习时长两年半的${this.child}`); }
Child.prototype.constructor = Child;
var parent = new Parent('father'); parent.say()
var child = new Child('cxk', 'father'); child.say()
|