要了解js繼承,一定先要去了解原型鏈,爲什麼呢?由於原型鏈是做爲實現繼承的主要方法。函數
如下幾點必定要謹記:那就是什麼是構造函數、什麼是原型、什麼是實例、以及他們之間的關係?this
繼承:利用原型讓一個引用類型繼承另外一個引用類型的屬性和方法spa
每一個構造函數都有一個原型對象:Person.prototype(prototype是指向原型對象的指針)prototype
原型對象都包含一個指向構造函數的指針:Person.prototype.constructor = Person指針
實例都包含一個指向原型對象的內部指針:var a = new Person();a._proto_ = Person.prototype對象
經過原型鏈實現繼承blog
function SuperType(){ this.colors = ["red","blue","green"]; } function SubType(){} SubType.prototype = new SuperType(); var instance = new SubType(); instance.colors.push("white"); console.log(instance.colors); //"red,blue,green,white" var instance2 = new SubType(); console.log(instance2.colors); //"red,blue,green,white"
借用構造函數繼承
function SuperType(name){ this.name = name; } function SubType(){ SuperType.call(this,"Lucy"); this.age = 20; } var instance = new SubType(); console.log(instance.name); //Lucy console.log(instance.age); //20
組合繼承原型鏈
組合繼承也叫做僞經典繼承,指的是將原型鏈和借用構造函數的技術組合在一塊兒的繼承模式,精髓是使用原型鏈實現對原型屬性和方法的繼承,經過借用構造函數來實現對實例屬性的繼承。原型
function SuperType(name){ this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(name,age){ SuperType.call(this,name); this.age = age; } SubType.prototype = new SuperType(); SubType.prototype.sayAge = function(){ console.log(this.age); } var instance = new SubType("Lucy",20); instance.colors.push("white"); console.log(instance.colors); //"red,blue,green,white" instance.sayName(); //Lucy instance.sayAge(); //20 var instance2 = new SubType("Tom",28); console.log(instance2.colors); //"red,blue,green" instance2.sayName(); //Tom instance2.sayAge(); //28