IVYGOU / JavaScript

Learning Notes for JavaScript
0 stars 0 forks source link

Subtype.prototype = SuperType.prototype?可否直接让两个原型属性相等? #17

Open IVYGOU opened 8 years ago

IVYGOU commented 8 years ago
function SuperType(){
  this.colors = ["red", "blue", "green"];
}

SuperType.prototype.foo = function() { console.log('foo');};

function SubType(){
  //inherit from SuperType
  SuperType.call(this);
}

Subtype.prototype = new SuperType();
var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); //”red,blue,green,black”

var instance2 = new SubType();
alert(instance2.colors); //”red,blue,green”

可不可以直接让Subtype.prototype = SuperType.prototype,两个原型相等。

IVYGOU commented 8 years ago

prototype chaining

IVYGOU commented 8 years ago

两个原型相等,会失去与构造函数之间的原型链