生活随笔
收集整理的這篇文章主要介紹了
javascrip --- 构造函数的继承
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
兩點需要注意的.
第一是在構(gòu)造函數(shù)聲明時,會同時創(chuàng)建一個該構(gòu)造函數(shù)的原型對象,而該原型對象是繼承自O(shè)bject的原型對象
// 聲明一個構(gòu)造函數(shù)Rectengle
function Rectangle(length, width) {this.length = length;this.width = width;
}// 即:看見function 后面函數(shù)名是大寫,一般認為其是一個構(gòu)造函數(shù),同時函數(shù)都會有一個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();
等號左側(cè)會有一個[[Prototype]]屬性(瀏覽器中可以使用__proto__讀取),指向P.prototype
// 于是,可以嘗試將左側(cè)的p改為一個自定義的構(gòu)造函數(shù),如下:// 自定義Rectangle構(gòu)造函數(shù)
function Rectangle(length, width) {this.length = length;this.width = width;
}// 給Rectangle的原型添加一個getArea()方法
Recangle.prototype.getArea = function() {return this.length* this.width;
}// Square構(gòu)造函數(shù)
function Square(size) {this.length = size;this.width = size;
}// Square繼承Rectangle(實際上是是Square的原型對象指向構(gòu)造函數(shù)Rectangle)
Square.prototype = new Rectangle();var sq1 = new Square(2);
console.log(sq1.getArea()); // 4// 執(zhí)行sq1.getArea()方法時,JavaScript引擎實際上是按如下方式工作的:
// 首先在sq1中尋找getArea(),未找到
// 在順著sq1的[[Prototype]]屬性,找到sq1的原型Square.prototype,并在原型中查找,未找到
// 數(shù)著Square.prototype的[[Prototype]]屬性找到其原型Rectangle.prototype,找到了..執(zhí)行g(shù)etArea()方法
所以繼承的實質(zhì)就是讓,A的原型對象(A.prototype)成為另一個構(gòu)造函數(shù)的實例,
就可以在A的實例中使用父元素的方法和屬性了
參考《JavaScript面向?qū)ο缶稰72~P73
總結(jié)
以上是生活随笔為你收集整理的javascrip --- 构造函数的继承的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。