原型是一種機制,JavaScript對象通過該機制彼此繼承特征。
在上一章中,我們學習了如何使用構(gòu)造函數(shù):
function User(fname, lname, age, loc) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.location = loc;
}
var Seagull = new User("Seagull", "Anna", 22, "New Delhi");
var tarush = new User("Tarush", "Balodhi", 34, "Bihar");測試看看?/?我們還了解到不能將新屬性添加到現(xiàn)有的對象構(gòu)造函數(shù)中:
User.weapon = "Sword";測試看看?/?
要向構(gòu)造函數(shù)添加新屬性,必須將其添加到構(gòu)造函數(shù)中:
function User(fname, lname, age, loc) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.location = loc;
this.weapon = "Sword";
}測試看看?/?有時我們想在后期向構(gòu)造函數(shù)添加新的屬性和方法,該構(gòu)造函數(shù)將在所有對象(示例)之間共享。答案是對象原型。
prototype屬性使您可以向構(gòu)造函數(shù)添加屬性和方法。
在此示例中,該prototype屬性允許您向User對象構(gòu)造函數(shù)添加新屬性:
function User(fname, lname, age, loc) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.location = loc;
}
User.prototype.weapon = "Sword";測試看看?/?在此示例中,該prototype屬性允許您向User對象構(gòu)造函數(shù)添加新方法:
function User(fname, lname, age, loc) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.location = loc;
}
User.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};測試看看?/?注意:僅修改您自己的原型。切勿修改標準(內(nèi)置)JavaScript對象的原型。