// 父类构造函数 function Parent(color) { this.color = color; this.print = function() { console.log(this.color); } }
如今要编写一个子类函数来继承这个父类,以下:ios
// 子类构造函数 function Son(color) { Parent.call(this, color); }
上面代码能够看到,子类Son是经过Parent.call的方式去调用父类构造函数,而后把this对象传进去,执行父类构造函数以后,子类Son就拥有了父类定义的color和print方法。es6
调用一下该方法,输出以下:面试
// 测试 var son1 = new Son('red'); son1.print(); // red var son2 = new Son('blue'); son2.print(); // blue
function Flower() { this.colors = ['黄色', '红色']; this.print = function () { console.log(this.colors) } } function Rose() { Flower.call(this); } var r1 = new Rose(); var r2 = new Rose(); console.log(r1.print()); // [ '黄色', '红色' ] console.log(r2.print()); // [ '黄色', '红色' ]
咱们如今有一个基类Flower,它有一个属性colors,如今咱们把某一个实例的colors值改一下:函数
r1.colors.push('紫色'); console.log(r1.print()); // [ '黄色', '红色', '紫色' ] console.log(r2.print()); // [ '黄色', '红色' ]
function Parent() { this.color = 'red'; this.print = function() { console.log(this.color); } } function Son() { }
咱们有一个父类和一个空的子类;性能
Son.prototype = new Parent(); Son.prototype.constructor = Son;
接着咱们把子函数的原型属性赋值给了父函数的实例;测试
var son1 = new Son(); son1.print(); // red
Son.prototype = new Parent(); Son.prototype.constructor = Son;
function Flower() { this.colors = ['黄色', '红色']; this.print = function () { console.log(this.colors) } } function Rose() {} Rose.prototype = new Flower(); Rose.prototype.constructor = Rose; var r1 = new Rose(); var r2 = new Rose(); console.log(r1.print()); // [ '黄色', '红色' ] console.log(r1.print()); // [ '黄色', '红色' ] r1.colors.push('紫色'); console.log(r1.print()); // [ '黄色', '红色', '紫色' ] console.log(r2.print()); // [ '黄色', '红色', '紫色' ]
function Parent(color) { this.color = color; } Parent.prototype.print = function() { console.log(this.color); } function Son(color) { Parent.call(this, color); } Son.prototype = new Parent(); Son.prototype.constructor = Son; var son1 = new Son('red'); son1.print(); // red var son2 = new Son('blue'); son2.print(); // blue
var obj = { color: 'red', print: function() { console.log(this.color); } }; var son1 = Object.create(obj); son1.print(); // red var son2 = Object.create(obj); son2.print(); // red
寄生式继承本质上仍是原型链继承,Object.create(obj);方法意思是以obj为原型构造对象,因此寄生式继承不须要构造函数,可是一样有着原型链继承的优缺点,也就是它把全部的属性和方法都共享了。this
function Parent(color) { this.color = color; } Parent.prototype.print = function() { console.log(this.color); } function Son(color) { Parent.call(this, color); } Son.prototype = Object.create(Parent.prototype); Son.prototype.constructor = Son; var son1 = new Son('red'); son1.print(); // red var son2 = new Son('blue'); son2.print(); // blue