兩點需要注意的.
第一是在構造函數聲明時,會同時創建一個該構造函數的原型對象,而該原型對象是繼承自Object的原型對象
// 聲明一個構造函數Rectengle
function Rectangle(length, width) {this.length = length;this.width = width;
}// 即:看見function 后面函數名是大寫,一般認為其是一個構造函數,同時函數都會有一個prototype屬性
// Rectangle.prototype的[[Prototype]]屬性默認指向Object.prototype屬性.
// 即:Rectangle.prototype.__proto__ === Object.prototype// 打印出來看看,,
console.log(Rectangle.prototype.__proto__ === Object.prototype);
console.log(Object.prototype.isPrototypeOf(Rectangle));
第二點是,使用new操作符,如 p = new P();
等號左側會有一個[[Prototype]]屬性(瀏覽器中可以使用__proto__讀取),指向P.prototype
// 于是,可以嘗試將左側的p改為一個自定義的構造函數,如下:// 自定義Rectangle構造函數
function Rectangle(length, width) {this.length = length;this.width = width;
}// 給Rectangle的原型添加一個getArea()方法
Recangle.prototype.getArea = function() {return this.length* this.width;
}// Square構造函數
function Square(size) {this.length = size;this.width = size;
}// Square繼承Rectangle(實際上是是Square的原型對象指向構造函數Rectangle)
Square.prototype = new Rectangle();var sq1 = new Square(2);
console.log(sq1.getArea()); // 4// 執行sq1.getArea()方法時,JavaScript引擎實際上是按如下方式工作的:
// 首先在sq1中尋找getArea(),未找到
// 在順著sq1的[[Prototype]]屬性,找到sq1的原型Square.prototype,并在原型中查找,未找到
// 數著Square.prototype的[[Prototype]]屬性找到其原型Rectangle.prototype,找到了..執行getArea()方法
所以繼承的實質就是讓,A的原型對象(A.prototype)成為另一個構造函數的實例,
就可以在A的實例中使用父元素的方法和屬性了
參考《JavaScript面向對象精要》P72~P73