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

JavaScript prototype

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

在前面的章節(jié)中我們學會了如何使用對象的構造器(constructor):

實例

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");

運行代碼 ?

我們也知道在一個已存在的對象構造器中是不能添加新的屬性的:

實例

Person.nationality = "English";

運行代碼 ?

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

實例

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

運行代碼 ?

prototype 繼承

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

  • Date 對象從 Date.prototype 繼承。
  • Array 對象從 Array.prototype 繼承。
  • Person 對象從 Person.prototype 繼承。

所有 JavaScript 中的對象都是位于原型鏈頂端的 Object 的實例。

JavaScript 對象有一個指向一個原型對象的鏈。當試圖訪問一個對象的屬性時,它不僅僅在該對象上搜尋,還會搜尋該對象的原型,以及該對象的原型的原型,依次層層向上搜索,直到找到一個名字匹配的屬性或到達原型鏈的末尾。

Date 對象, Array 對象, 以及 Person 對象從 Object.prototype 繼承。

添加屬性和方法

有的時候我們想要在所有已經存在的對象添加新的屬性或方法。

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

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

實例

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

運行代碼 ?

當然我們也可以使用 prototype 屬性就可以給對象的構造函數(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; };

運行代碼 ?