原型是一種機(jī)制,JavaScript對(duì)象通過(guò)該機(jī)制彼此繼承特征。
在上一章中,我們學(xué)習(xí)了如何使用構(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");測(cè)試看看?/?
我們還了解到不能將新屬性添加到現(xiàn)有的對(duì)象構(gòu)造函數(shù)中:
User.weapon = "Sword";測(cè)試看看?/?
要向構(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"; }測(cè)試看看?/?
有時(shí)我們想在后期向構(gòu)造函數(shù)添加新的屬性和方法,該構(gòu)造函數(shù)將在所有對(duì)象(示例)之間共享。答案是對(duì)象原型。
prototype屬性使您可以向構(gòu)造函數(shù)添加屬性和方法。
在此示例中,該prototype屬性允許您向User對(duì)象構(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";測(cè)試看看?/?
在此示例中,該prototype屬性允許您向User對(duì)象構(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; };測(cè)試看看?/?
注意:僅修改您自己的原型。切勿修改標(biāo)準(zhǔn)(內(nèi)置)JavaScript對(duì)象的原型。