function Parent(name) { this.name = name; // 会被实例共享但不会被修改 } Parent.prototype = function () { console.log('name ', this.name); }
构造函数继承
1 2 3 4 5 6 7
function Child(name, sex) { Parent.call(this, name); this.sex = sex; } Child.prototype.say = function () { console.log('My name is ', this.name); }
通过构造函数相当于重写了整个对象,但是在继承的过程中对于父类中的方法却不需要重写
原型链继承
1 2 3 4 5 6 7
function Child(name, sex) { this.sex = sex; } Child.prototype = new Parent(); Child.prototype.say = function () { console.log('My name is ', this.name); }
function Child(name, sex) { Parent.call(this, name); this.sex = sex; } Child.prototype = new Parent(); Child.prototype.say = function () { console.log('My name is ', this.name); }