在閱讀這篇文章時(shí)摆霉,請你先清空腦中所有對原型一知半解的印象,首先來看Javascript中函數(shù)所具有的一個(gè)屬性:prototype
.
先看下面這個(gè)例子:
function f() { } // define a function f
console.log(f.prototype.constructor === f); // true
當(dāng)我們創(chuàng)建一個(gè)函數(shù)f
究珊,這個(gè)函數(shù)會自動具有一個(gè)屬性prototype
荆萤,這個(gè)屬性即為函數(shù)f
的原型感猛。并且這個(gè)它的原型自動會具有一個(gè)屬性constructor
,指向函數(shù)f
没龙。這里我們可以看出一種一一對應(yīng)關(guān)系铺厨,即一個(gè)函數(shù)具有一個(gè)原型缎玫,而這個(gè)原型又通過屬性constructor
指明它是哪一個(gè)函數(shù)的原型。
可是原型有什么用呢解滓?讓我們來看一個(gè)創(chuàng)建對象的例子:
function Car(brand, year) {
this.brand = brand;
this.year = year;
} // 定義一個(gè)函數(shù)Car
let car = new Car("瑪莎拉蒂", 2014); // 從函數(shù)Car創(chuàng)建一個(gè)對象
console.log(car.brand); // 瑪莎拉蒂
console.log(car.year); // 2014
console.log(car.has_wheels); // undefined赃磨,因?yàn)槲覀儧]有定義has_wheels屬性
car.drive(); // 報(bào)錯(cuò),因?yàn)槲覀儧]有定義drive函數(shù)
上面的代碼中洼裤,brand
和year
都是每一輛車所獨(dú)有的邻辉,但屬性has_wheels
與函數(shù)drive
剛是所有的車所共有的。下面的代碼展示了腮鞍,如何用原型來實(shí)現(xiàn)這種“共有”的屬性和函數(shù)值骇。
function Car(brand, year) {
this.brand = brand;
this.year = year;
} // 定義一個(gè)函數(shù)Car
Car.prototype.has_wheels = true;
Car.prototype.drive = function() {
console.log("driving...");
}
let car = new Car("瑪莎拉蒂", 2014); // 從函數(shù)Car創(chuàng)建一個(gè)對象
console.log(car.brand); // 瑪莎拉蒂
console.log(car.year); // 2014
console.log(car.has_wheels); // true
car.drive(); // 打印出driving
從上面的代碼,我們可以很容易地了解到Javascript對于面向?qū)ο蟮脑O(shè)計(jì)思想移国,那就是
- 使用new函數(shù)并配合構(gòu)造函數(shù)(constructor)來創(chuàng)建對象吱瘩,
- 運(yùn)行構(gòu)造函數(shù)(constructor)來設(shè)置對象“獨(dú)有”的屬性和方法,
- 對構(gòu)造函數(shù)(constructor)的
prototype
進(jìn)行更改可以對所有由它創(chuàng)建的對象設(shè)置“共有”的屬性和方法迹缀。
要注意的是使碾,只有函數(shù)有prototype
屬性,也就是說只有函數(shù)有原型裹芝,而非函數(shù)的對象是沒有的部逮。
更多關(guān)于原型的探討請參見: