中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

JavaScript prototype

所有的 JavaScript 對(duì)象都會(huì)從一個(gè) prototype(原型對(duì)象)中繼承屬性和方法。

在前面的章節(jié)中我們學(xué)會(huì)了如何使用對(duì)象的構(gòu)造器(constructor):

實(shí)例

function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green");

運(yùn)行代碼 ?

我們也知道在一個(gè)已存在的對(duì)象構(gòu)造器中是不能添加新的屬性的:

實(shí)例

Person.nationality = "English";

運(yùn)行代碼 ?

要添加一個(gè)新的屬性需要在在構(gòu)造器函數(shù)中添加:

實(shí)例

function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; this.nationality = "English"; }

運(yùn)行代碼 ?

prototype 繼承

所有的 JavaScript 對(duì)象都會(huì)從一個(gè) prototype(原型對(duì)象)中繼承屬性和方法:

  • Date 對(duì)象從 Date.prototype 繼承。
  • Array 對(duì)象從 Array.prototype 繼承。
  • Person 對(duì)象從 Person.prototype 繼承。

所有 JavaScript 中的對(duì)象都是位于原型鏈頂端的 Object 的實(shí)例。

JavaScript 對(duì)象有一個(gè)指向一個(gè)原型對(duì)象的鏈。當(dāng)試圖訪問一個(gè)對(duì)象的屬性時(shí),它不僅僅在該對(duì)象上搜尋,還會(huì)搜尋該對(duì)象的原型,以及該對(duì)象的原型的原型,依次層層向上搜索,直到找到一個(gè)名字匹配的屬性或到達(dá)原型鏈的末尾。

Date 對(duì)象, Array 對(duì)象, 以及 Person 對(duì)象從 Object.prototype 繼承。

添加屬性和方法

有的時(shí)候我們想要在所有已經(jīng)存在的對(duì)象添加新的屬性或方法。

另外,有時(shí)候我們想要在對(duì)象的構(gòu)造函數(shù)中添加屬性或方法。

使用 prototype 屬性就可以給對(duì)象的構(gòu)造函數(shù)添加新的屬性:

實(shí)例

function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } Person.prototype.nationality = "English";

運(yùn)行代碼 ?

當(dāng)然我們也可以使用 prototype 屬性就可以給對(duì)象的構(gòu)造函數(shù)添加新的方法:

實(shí)例

function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } Person.prototype.name = function() { return this.firstName + " " + this.lastName; };

運(yùn)行代碼 ?