全面講解JavaScript原型與原型鏈
一. 普通對象與函數(shù)對象
JavaScript 中,萬物皆對象!但對象也是有區(qū)別的。分為普通對象和函數(shù)對象,Object 、Function 是 JS 自帶的函數(shù)對象。下面舉例說明
var o1 = {}; var o2 =new Object(); var o3 = new f1(); function f1(){}; var f2 = function(){}; var f3 = new Function('str','console.log(str)'); console.log(typeof Object); //function console.log(typeof Function); //function console.log(typeof f1); //function console.log(typeof f2); //function console.log(typeof f3); //function console.log(typeof o1); //object console.log(typeof o2); //object console.log(typeof o3); //object
在上面的例子中 o1 o2 o3 為普通對象,f1 f2 f3 為函數(shù)對象。怎么區(qū)分,其實很簡單,凡是通過 new Function() 創(chuàng)建的對象都是函數(shù)對象,其他的都是普通對象。f1,f2,歸根結底都是通過 new Function()的方式進行創(chuàng)建的。Function Object 也都是通過 New Function()創(chuàng)建的。
一定要分清楚普通對象和函數(shù)對象,下面我們會常常用到它。
二. 構造函數(shù)
我們先復習一下構造函數(shù)的知識:
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function() { alert(this.name) } } var person1 = new Person('Zaxlct', 28, 'Software Engineer'); var person2 = new Person('Mick', 23, 'Doctor');
上面的例子中 person1 和 person2 都是 Person 的實例。這兩個實例都有一個 constructor
(構造函數(shù))屬性,該屬性(是一個指針)指向 Person。 即:
console.log(person1.constructor == Person); //true console.log(person2.constructor == Person); //true
我們要記住兩個概念(構造函數(shù),實例):
person1 和 person2 都是 構造函數(shù) Person 的實例
一個公式:
實例的構造函數(shù)屬性(constructor)指向構造函數(shù)。
三. 原型對象
在 JavaScript 中,每當定義一個對象(函數(shù)也是對象)時候,對象中都會包含一些預定義的屬性。其中每個函數(shù)對象都有一個prototype
屬性,這個屬性指向函數(shù)的原型對象。(先用不管什么是 __proto__
第二節(jié)的課程會詳細的剖析)
function Person() {} Person.prototype.name = 'Zaxlct'; Person.prototype.age = 28; Person.prototype.job = 'Software Engineer'; Person.prototype.sayName = function() { alert(this.name); } var person1 = new Person(); person1.sayName(); // 'Zaxlct' var person2 = new Person(); person2.sayName(); // 'Zaxlct' console.log(person1.sayName == person2.sayName); //true
我們得到了本文第一個「定律」:
每個對象都有 __proto__ 屬性,但只有函數(shù)對象才有 prototype 屬性
那什么是原型對象呢?
我們把上面的例子改一改你就會明白了:
Person.prototype = { name: 'Zaxlct', age: 28, job: 'Software Engineer', sayName: function() { alert(this.name); } }
原型對象,顧名思義,它就是一個普通對象(廢話 = =!)。從現(xiàn)在開始你要牢牢記住原型對象就是 Person.prototype ,如果你還是害怕它,那就把它想想成一個字母 A: var A = Person.prototype
在上面我們給 A 添加了 四個屬性:name、age、job、sayName。其實它還有一個默認的屬性:constructor
在默認情況下,所有的原型對象都會自動獲得一個
constructor
(構造函數(shù))屬性,這個屬性(是一個指針)指向prototype
屬性所在的函數(shù)(Person)
上面這句話有點拗口,我們「翻譯」一下:A 有一個默認的 constructor
屬性,這個屬性是一個指針,指向 Person。即:Person.prototype.constructor == Person
在上面第二小節(jié)《構造函數(shù)》里,我們知道實例的構造函數(shù)屬性(constructor)指向構造函數(shù) :person1.constructor == Person
這兩個「公式」好像有點聯(lián)系:
person1.constructor == Person Person.prototype.constructor == Person
person1 為什么有 constructor 屬性?那是因為 person1 是 Person 的實例。
那 Person.prototype 為什么有 constructor 屬性??同理, Person.prototype (你把它想象成 A) 也是Person 的實例。
也就是在 Person 創(chuàng)建的時候,創(chuàng)建了一個它的實例對象并賦值給它的 prototype,基本過程如下:
var A = new Person(); Person.prototype = A; // 注:上面兩行代碼只是幫助理解,并不能正常運行
結論:原型對象(Person.prototype)是 構造函數(shù)(Person)的一個實例。
原型對象其實就是普通對象(但 Function.prototype 除外,它是函數(shù)對象,但它很特殊,他沒有prototype屬性(前面說道函數(shù)對象都有prototype屬性))??聪旅娴睦樱?/p>
function Person(){}; console.log(Person.prototype) //Person{} console.log(typeof Person.prototype) //Object console.log(typeof Function.prototype) // Function,這個特殊 console.log(typeof Object.prototype) // Object console.log(typeof Function.prototype.prototype) //undefined
Function.prototype
為什么是函數(shù)對象呢?
var A = new Function (); Function.prototype = A;
上文提到凡是通過 new Function( ) 產生的對象都是函數(shù)對象。因為 A 是函數(shù)對象,所以
Function.prototype
是函數(shù)對象。
那原型對象是用來做什么的呢?主要作用是用于繼承。舉個例子:
var Person = function(name){ this.name = name; // tip: 當函數(shù)執(zhí)行時這個 this 指的是誰? }; Person.prototype.getName = function(){ return this.name; // tip: 當函數(shù)執(zhí)行時這個 this 指的是誰? } var person1 = new person('Mick'); person1.getName(); //Mick
從這個例子可以看出,通過給 Person.prototype
設置了一個函數(shù)對象的屬性,那有 Person 的實例(person1)出來的普通對象就繼承了這個屬性。具體是怎么實現(xiàn)的繼承,就要講到下面的原型鏈了。
小問題,上面兩個 this 都指向誰?
var person1 = new person('Mick'); person1.name = 'Mick'; // 此時 person1 已經有 name 這個屬性了 person1.getName(); //Mick
故兩次 this 在函數(shù)執(zhí)行時都指向 person1。
四. __proto__
JS 在創(chuàng)建對象(不論是普通對象還是函數(shù)對象)的時候,都有一個叫做__proto__
的內置屬性,用于指向創(chuàng)建它的構造函數(shù)的原型對象。
對象 person1 有一個 __proto__
屬性,創(chuàng)建它的構造函數(shù)是 Person,構造函數(shù)的原型對象是 Person.prototype ,所以:person1.__proto__ == Person.prototype
請看下圖:
根據上面這個連接圖,我們能得到:
Person.prototype.constructor == Person; person1.__proto__ == Person.prototype; person1.constructor == Person;
不過,要明確的真正重要的一點就是,這個連接存在于實例(person1
)與構造函數(shù)(Person
)的原型對象(Person.prototype
)之間,而不是存在于實例(person1
)與構造函數(shù)(Person
)之間。
注意:因為絕大部分瀏覽器都支持__proto__屬性,所以它才被加入了 ES6 里(ES5 部分瀏覽器也支持,但還不是標準)。
五. 構造器
熟悉 Javascript 的童鞋都知道,我們可以這樣創(chuàng)建一個對象:
var obj = {}
它等同于下面這樣:
var obj = new Object()
obj 是構造函數(shù)(Object)的一個實例。所以:
obj.constructor === Object obj.__proto__ === Object.prototype
新對象 obj 是使用 new 操作符后跟一個構造函數(shù)來創(chuàng)建的。構造函數(shù)(Object)本身就是一個函數(shù)(就是上面說的函數(shù)對象),它和上面的構造函數(shù) Person 差不多。只不過該函數(shù)是出于創(chuàng)建新對象的目的而定義的。所以不要被 Object 嚇倒。
同理,可以創(chuàng)建對象的構造器不僅僅有 Object,也可以是 Array,Date,F(xiàn)unction等。
所以我們也可以構造函數(shù)來創(chuàng)建 Array、 Date、Function
var b = new Array(); b.constructor === Array; b.__proto__ === Array.prototype; var c = new Date(); c.constructor === Date; c.__proto__ === Date.prototype; var d = new Function(); d.constructor === Function; d.__proto__ === Function.prototype;
這些構造器都是函數(shù)對象:
六. 原型鏈
小測試來檢驗一下你理解的怎么樣:
person1.__proto__
是什么?Person.__proto__
是什么?Person.prototype.__proto__
是什么?Object.__proto__
是什么?Object.prototype__proto__
是什么?
答案:
第一題:
因為person1.__proto__ === person1 的構造函數(shù).prototype
因為person1的構造函數(shù) === Person
所以person1.__proto__ === Person.prototype
第二題:
因為Person.__proto__ === Person的構造函數(shù).prototype
因為Person的構造函數(shù) === Function
所以Person.__proto__ === Function.prototype
第三題:
Person.prototype
是一個普通對象,我們無需關注它有哪些屬性,只要記住它是一個普通對象。
因為一個普通對象的構造函數(shù) === Object
所以Person.prototype.__proto__ === Object.prototype
第四題,參照第二題,因為 Person 和 Object 一樣都是構造函數(shù)
第五題:
Object.prototype
對象也有proto屬性,但它比較特殊,為 null 。因為 null 處于原型鏈的頂端,這個只能記住。Object.prototype.__proto__ === null
七. 函數(shù)對象 (復習一下前面的知識點)
所有函數(shù)對象的proto都指向Function.prototype,它是一個空函數(shù)(Empty function)
Number.__proto__ === Function.prototype // true Number.constructor == Function //true Boolean.__proto__ === Function.prototype // true Boolean.constructor == Function //true String.__proto__ === Function.prototype // true String.constructor == Function //true // 所有的構造器都來自于Function.prototype,甚至包括根構造器Object及Function自身 Object.__proto__ === Function.prototype // true Object.constructor == Function // true // 所有的構造器都來自于Function.prototype,甚至包括根構造器Object及Function自身 Function.__proto__ === Function.prototype // true Function.constructor == Function //true Array.__proto__ === Function.prototype // true Array.constructor == Function //true RegExp.__proto__ === Function.prototype // true RegExp.constructor == Function //true Error.__proto__ === Function.prototype // true Error.constructor == Function //true Date.__proto__ === Function.prototype // true Date.constructor == Function //true
JavaScript中有內置(build-in)構造器/對象共計12個(ES5中新加了JSON),這里列舉了可訪問的8個構造器。剩下如Global不能直接訪問,Arguments僅在函數(shù)調用時由JS引擎創(chuàng)建,Math,JSON是以對象形式存在的,無需new。它們的proto是Object.prototype。如下
Math.__proto__ === Object.prototype // true Math.construrctor == Object // true JSON.__proto__ === Object.prototype // true JSON.construrctor == Object //true
上面說的函數(shù)對象當然包括自定義的。如下
// 函數(shù)聲明 function Person() {} // 函數(shù)表達式 var Perosn = function() {} console.log(Person.__proto__ === Function.prototype) // true console.log(Man.__proto__ === Function.prototype) // true
這說明什么呢?
所有的構造器都來自于 Function.prototype
,甚至包括根構造器Object
及Function
自身。所有構造器都繼承了·Function.prototype·的屬性及方法。如length、call、apply、bind
Function.prototype
也是唯一一個typeof XXX.prototype
為 function
的prototype
。其它的構造器的prototype
都是一個對象
console.log(typeof Function.prototype) // function console.log(typeof Object.prototype) // object console.log(typeof Number.prototype) // object console.log(typeof Boolean.prototype) // object console.log(typeof String.prototype) // object console.log(typeof Array.prototype) // object console.log(typeof RegExp.prototype) // object console.log(typeof Error.prototype) // object console.log(typeof Date.prototype) // object console.log(typeof Object.prototype) // object
噢,上面還提到它是一個空的函數(shù),console.log(Function.prototype)
下看看
知道了所有構造器(含內置及自定義)的__proto__
都是Function.prototype
,那Function.prototype
的__proto__
是誰呢?
相信都聽說過JavaScript中函數(shù)也是一等公民,那從哪能體現(xiàn)呢?如下
console.log(Function.prototype.__proto__ === Object.prototype) // true
這說明所有的構造器也都是一個普通 JS 對象,可以給構造器添加/刪除屬性等。同時它也繼承了Object.prototype上的所有方法:toString、valueOf、hasOwnProperty等。
最后Object.prototype的proto是誰?
Object.prototype.__proto__ === null // true
已經到頂了,為null。(讀到現(xiàn)在,再回過頭看第五章,能明白嗎?)
八. Prototype
在 ECMAScript 核心所定義的全部屬性中,最耐人尋味的就要數(shù)
prototype
屬性了。對于 ECMAScript 中的引用類型而言,prototype
是保存著它們所有實例方法的真正所在。換句話所說,諸如toString()
和valuseOf()
等方法實際上都保存在prototype
名下,只不過是通過各自對象的實例訪問罷了。
——《JavaScript 高級程序設計》第三版 P116
我們知道 JS 內置了一些方法供我們使用,比如:
對象可以用 constructor/toString()/valueOf()
等方法;
數(shù)組可以用 map()/filter()/reducer()
等方法;
數(shù)字可用用 parseInt()/parseFloat()
等方法;
當我們創(chuàng)建一個函數(shù)時:
var Person = new Object()
Person
是 Object
的實例,所以 Person
繼承了Object
的原型對象Object.prototype
上所有的方法:
Object 的每個實例都具有以上的屬性和方法。
所以我可以用 Person.constructor
也可以用 Person.hasOwnProperty
。
當我們創(chuàng)建一個數(shù)組時:
var num = new Array()
num
是 Array
的實例,所以 num
繼承了Array
的原型對象Array.prototype
上所有的方法:
怎么是一個空數(shù)組???
我們可以用一個 ES5 提供的新方法:Object.getOwnPropertyNames
獲取所有(包括不可枚舉的屬性)的屬性名不包括 prototy
中的屬性,返回一個數(shù)組:
var arrayAllKeys = Array.prototype; // [] 空數(shù)組 // 只得到 arrayAllKeys 這個對象里所有的屬性名(不會去找 arrayAllKeys.prototype 中的屬性) console.log(Object.getOwnPropertyNames(arrayAllKeys)); /* 輸出: ["length", "constructor", "toString", "toLocaleString", "join", "pop", "push", "concat", "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", "some", "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight", "entries", "keys", "copyWithin", "find", "findIndex", "fill"] */
這樣你就明白了隨便聲明一個數(shù)組,它為啥能用那么多方法了。
細心的你肯定發(fā)現(xiàn)了Object.getOwnPropertyNames(arrayAllKeys)
輸出的數(shù)組里并沒有 constructor/hasOwnPrototype
等對象的方法(你肯定沒發(fā)現(xiàn))。
但是隨便定義的數(shù)組也能用這些方法
var num = [1]; console.log(num.hasOwnPrototype()) // false (輸出布爾值而不是報錯)
因為Array.prototype
雖然沒這些方法,但是它有原型對象(__proto__
):
// 上面我們說了 Object.prototype 就是一個普通對象。 Array.prototype.__proto__ == Object.prototype
所以 Array.prototype
繼承了對象的所有方法,當你用num.hasOwnPrototype()
時,JS 會先查一下它的構造函數(shù) (Array
) 的原型對象 Array.prototype
有沒有有hasOwnPrototype()
方法,沒查到的話繼續(xù)查一下 Array.prototype
的原型對象 Array.prototype.__proto__
有沒有這個方法。
當我們創(chuàng)建一個函數(shù)時:
var f = new Function("x","return x*x;"); //當然你也可以這么創(chuàng)建 f = function(x){ return x*x } console.log(f.arguments) // arguments 方法從哪里來的? console.log(f.call(window)) // call 方法從哪里來的? console.log(Function.prototype) // function() {} (一個空的函數(shù)) console.log(Object.getOwnPropertyNames(Function.prototype)); /* 輸出 ["length", "name", "arguments", "caller", "constructor", "bind", "toString", "call", "apply"] */
我們再復習第八小節(jié)這句話:
所有函數(shù)對象 proto都指向
Function.prototype
,它是一個空函數(shù)(Empty function)
嗯,我們驗證了它就是空函數(shù)。不過不要忽略前半句。我們枚舉出了它的所有的方法,所以所有的函數(shù)對象都能用,比如:
函數(shù)對象
如果你還沒搞懂啥是函數(shù)對象,那我也不知道怎么拯救你了。
還有,我建議你可以再復習下為什么:
Function.prototype 是唯一一個typeof XXX.prototype為 “function”的prototype
我猜你肯定忘了。
九. 復習一下
第八小節(jié)我們總結了:所有函數(shù)對象的 __proto__ 都指向 Function.prototype,它是一個空函數(shù)(Empty function)
但是你可別忘了在第三小節(jié)我們總結的:所有對象的 __proto__ 都指向其構造器的 prototype
咦,我找了半天怎么沒找到這句話……我們下面再復習下這句話。
先看看 JS 內置構造器:
var obj = {name: 'jack'} var arr = [1,2,3] var reg = /hello/g var date = new Date var err = new Error('exception') console.log(obj.__proto__ === Object.prototype) // true console.log(arr.__proto__ === Array.prototype) // true console.log(reg.__proto__ === RegExp.prototype) // true console.log(date.__proto__ === Date.prototype) // true console.log(err.__proto__ === Error.prototype) // true
再看看自定義的構造器,這里定義了一個 Person
:
function Person(name) { this.name = name; } var p = new Person('jack') console.log(p.__proto__ === Person.prototype) // true
p
是 Person
的實例對象,p
的內部原型總是指向其構造器 Person
的原型對象 prototype
。
每個對象都有一個 constructor
屬性,可以獲取它的構造器,因此以下打印結果也是恒等的:
function Person(name) { this.name = name } var p = new Person('jack') console.log(p.__proto__ === p.constructor.prototype) // true
上面的Person
沒有給其原型添加屬性或方法,這里給其原型添加一個getName
方法:
function Person(name) { this.name = name } // 修改原型 Person.prototype.getName = function() {} var p = new Person('jack') console.log(p.__proto__ === Person.prototype) // true console.log(p.__proto__ === p.constructor.prototype) // true
可以看到p.__proto__
與Person.prototype
,p.constructor.prototype
都是恒等的,即都指向同一個對象。
如果換一種方式設置原型,結果就有些不同了:
function Person(name) { this.name = name } // 重寫原型 Person.prototype = { getName: function() {} } var p = new Person('jack') console.log(p.__proto__ === Person.prototype) // true console.log(p.__proto__ === p.constructor.prototype) // false
這里直接重寫了 Person.prototype
(注意:上一個示例是修改原型)。輸出結果可以看出p.__proto__
仍然指向的是Person.prototype
,而不是p.constructor.prototype
。
這也很好理解,給Person.prototype
賦值的是一個對象直接量{getName: function(){}}
,使用對象直接量方式定義的對象其構造器(constructor
)指向的是根構造器Object
,Object.prototype
是一個空對象{}
,{}
自然與{getName: function(){}}
不等。如下:
var p = {} console.log(Object.prototype) // 為一個空的對象{} console.log(p.constructor === Object) // 對象直接量方式定義的對象其constructor為Object console.log(p.constructor.prototype === Object.prototype) // 為true,不解釋(?ˇ3ˇ?)
十. 原型鏈(再復習一下:)
下面這個例子你應該能明白了!
function Person(){} var person1 = new Person(); console.log(person1.__proto__ === Person.prototype); // true console.log(Person.prototype.__proto__ === Object.prototype) //true console.log(Object.prototype.__proto__) //null Person.__proto__ == Function.prototype; //true console.log(Function.prototype)// function(){} (空函數(shù)) var num = new Array() console.log(num.__proto__ == Array.prototype) // true console.log( Array.prototype.__proto__ == Object.prototype) // true console.log(Array.prototype) // [] (空數(shù)組) console.log(Object.prototype.__proto__) //null console.log(Array.__proto__ == Function.prototype)// true
疑點解惑:
Object.__proto__ === Function.prototype // true
Object
是函數(shù)對象,是通過new Function()
創(chuàng)建的,所以Object.__proto__
指向Function.prototype
。(參照第八小節(jié):「所有函數(shù)對象的__proto__
都指向Function.prototype
」)
Function.__proto__ === Function.prototype // true
Function
也是對象函數(shù),也是通過new Function()
創(chuàng)建,所以Function.__proto__
指向Function.prototype
。
自己是由自己創(chuàng)建的,好像不符合邏輯,但仔細想想,現(xiàn)實世界也有些類似,你是怎么來的,你媽生的,你媽怎么來的,你姥姥生的,……類人猿進化來的,那類人猿從哪來,一直追溯下去……,就是無,(NULL生萬物)
正如《道德經》里所說“無,名天地之始”。
Function.prototype.__proto__ === Object.prototype //true
其實這一點我也有點困惑,不過也可以試著解釋一下。
Function.prototype
是個函數(shù)對象,理論上他的__proto__
應該指向Function.prototype
,就是他自己,自己指向自己,沒有意義。
JS一直強調萬物皆對象,函數(shù)對象也是對象,給他認個祖宗,指向Object.prototype
。Object.prototype.__proto__ === null
,保證原型鏈能夠正常結束。
十一 總結
- 原型和原型鏈是JS實現(xiàn)繼承的一種模型。
- 原型鏈的形成是真正是靠
__proto__
而非prototype
要深入理解這句話,我們再舉個例子,看看前面你真的理解了嗎?
var animal = function(){}; var dog = function(){}; animal.price = 2000; dog.prototype = animal; var tidy = new dog(); console.log(dog.price) //undefined console.log(tidy.price) // 2000
這里解釋一下:
var dog = function(){}; dog.prototype.price = 2000; var tidy = new dog(); console.log(tidy.price); // 2000 console.log(dog.price); //undefined
var dog = function(){}; var tidy = new dog(); tidy.price = 2000; console.log(dog.price); //undefined
這個明白吧?想一想我們上面說過這句話:
實例(
tidy
)和 原型對象(dog.prototype
)存在一個連接。不過,要明確的真正重要的一點就是,這個連接存在于實例(tidy
)與構造函數(shù)的原型對象(dog.prototype
)之間,而不是存在于實例(tidy
)與構造函數(shù)(dog
)之間。
聰明的你肯定想通了吧。
到此這篇關于全面講解JavaScript原型與原型鏈的文章就介紹到這了,更多相關JavaScript原型與原型鏈內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript私有屬性的實現(xiàn)方式及對比詳解
在 JavaScript 中,私有屬性是指只能在類或對象內部訪問的屬性,外部無法直接訪問或修改,隨著 JavaScript 語言的發(fā)展,實現(xiàn)私有屬性的方式也在不斷演進,本文將介紹幾種常見的實現(xiàn)私有屬性的方法,并對比它們的優(yōu)缺點,幫助開發(fā)者選擇適合的方案,需要的朋友可以參考下2025-03-03Javascript和Java獲取各種form表單信息的簡單實例
本篇文章主要是對Javascript和Java獲取各種form表單信息的簡單實例進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-02-02淺談javascript中l(wèi)odash與lodash-es的區(qū)別
本文主要介紹了javascript中l(wèi)odash與lodash-es的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-10-10Flow之一個新的Javascript靜態(tài)類型檢查器
今天我們興奮的發(fā)布了 Flow 的嘗鮮版,一個新的Javascript靜態(tài)類型檢查器。Flow為Javascript添加了靜態(tài)類型檢查,以提高開發(fā)效率和代碼質量,本文給大家分享Flow之一個新的Javascript靜態(tài)類型檢查器,感興趣的朋友一起學習吧2015-12-12JS事件循環(huán)機制event loop宏任務微任務原理解析
這篇文章主要介紹了JS事件循環(huán)機制event loop宏任務微任務原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08使用Javascript開發(fā)sliding-nav帶滑動條效果的導航插件
這篇文章主要介紹了使用Javascript開發(fā)sliding-nav帶滑動條效果的導航插件,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03