JavaScript 中,萬物皆對象!但對象也是有區別的。分爲普通對象和函數對象,Object 、Function 是 JS 自帶的函數對象。下面舉例說明javascript
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 爲函數對象。怎麼區分,其實很簡單,凡是經過 new Function() 建立的對象都是函數對象,其餘的都是普通對象。f1,f2,歸根結底都是經過 new Function()的方式進行建立的。Function Object 也都是經過 New Function()建立的。java
必定要分清楚普通對象和函數對象,下面咱們會經常用到它。數組
咱們先複習一下構造函數的知識:瀏覽器
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
(構造函數)屬性,該屬性(是一個指針)指向 Person。 即:app
console.log(person1.constructor == Person); //true console.log(person2.constructor == Person); //true
咱們要記住兩個概念(構造函數,實例):
person1 和 person2 都是 構造函數 Person 的實例
一個公式:
實例的構造函數屬性(constructor)指向構造函數。函數
在 JavaScript 中,每當定義一個對象(函數也是對象)時候,對象中都會包含一些預約義的屬性。其中每一個函數對象都有一個prototype
屬性,這個屬性指向函數的原型對象。(先用無論什麼是 __proto__
第二節的課程會詳細的剖析)測試
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
咱們獲得了本文第一個「定律」:ui
每一個對象都有 __proto__ 屬性,但只有函數對象纔有 prototype 屬性
那什麼是原型對象呢?
咱們把上面的例子改一改你就會明白了:this
Person.prototype = { name: 'Zaxlct', age: 28, job: 'Software Engineer', sayName: function() { alert(this.name); } }
原型對象,顧名思義,它就是一個普通對象(廢話 = =!)。從如今開始你要緊緊記住原型對象就是 Person.prototype ,若是你仍是懼怕它,那就把它想一想成一個字母 A: var A = Person.prototype
spa
在上面咱們給 A 添加了 四個屬性:name、age、job、sayName。其實它還有一個默認的屬性:constructor
在默認狀況下,全部的原型對象都會自動得到一個
constructor
(構造函數)屬性,這個屬性(是一個指針)指向prototype
屬性所在的函數(Person)
上面這句話有點拗口,咱們「翻譯」一下:A 有一個默認的 constructor
屬性,這個屬性是一個指針,指向 Person。即:
Person.prototype.constructor == Person
在上面第二小節《構造函數》裏,咱們知道實例的構造函數屬性(constructor)指向構造函數 :person1.constructor == Person
這兩個「公式」好像有點聯繫:
person1.constructor == Person Person.prototype.constructor == Person
person1 爲何有 constructor 屬性?那是由於 person1 是 Person 的實例。
那 Person.prototype 爲何有 constructor 屬性??同理, Person.prototype (你把它想象成 A) 也是Person 的實例。
也就是在 Person 建立的時候,建立了一個它的實例對象並賦值給它的 prototype,基本過程以下:
var A = new Person(); Person.prototype = A;
結論:原型對象(Person.prototype)是 構造函數(Person)的一個實例。
原型對象其實就是普通對象(但 Function.prototype 除外,它是函數對象,但它很特殊,他沒有prototype屬性(前面說道函數對象都有prototype屬性))。看下面的例子:
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
爲何是函數對象呢?
var A = new Function (); Function.prototype = A;
Function.prototype
是函數對象。那原型對象是用來作什麼的呢?主要做用是用於繼承。舉個例子:
var Person = function(name){ this.name = name; // tip: 當函數執行時這個 this 指的是誰? }; Person.prototype.getName = function(){ return this.name; // tip: 當函數執行時這個 this 指的是誰? } var person1 = new person('Mick'); person1.getName(); //Mick
從這個例子能夠看出,經過給 Person.prototype
設置了一個函數對象的屬性,那有 Person 的實例(person1)出來的普通對象就繼承了這個屬性。具體是怎麼實現的繼承,就要講到下面的原型鏈了。
小問題,上面兩個 this 都指向誰?
var person1 = new person('Mick'); person1.name = 'Mick'; // 此時 person1 已經有 name 這個屬性了 person1.getName(); //Mick
故兩次 this 在函數執行時都指向 person1。
JS 在建立對象(不管是普通對象仍是函數對象)的時候,都有一個叫作__proto__
的內置屬性,用於指向建立它的構造函數的原型對象。
對象 person1 有一個 __proto__
屬性,建立它的構造函數是 Person,構造函數的原型對象是 Person.prototype ,因此:
person1.__proto__ == Person.prototype
請看下圖:
根據上面這個鏈接圖,咱們能獲得:
Person.prototype.constructor == Person; person1.__proto__ == Person.prototype; person1.constructor == Person;
不過,要明確的真正重要的一點就是,這個鏈接存在於實例(person1
)與構造函數(Person
)的原型對象(Person.prototype
)之間,而不是存在於實例(person1
)與構造函數(Person
)之間。
注意:由於絕大部分瀏覽器都支持__proto__屬性,因此它才被加入了 ES6 裏(ES5 部分瀏覽器也支持,但還不是標準)。
熟悉 Javascript 的童鞋都知道,咱們能夠這樣建立一個對象:
var obj = {}
它等同於下面這樣:
var obj = new Object()
obj 是構造函數(Object)的一個實例。因此:
obj.constructor === Object
obj.__proto__ === Object.prototype
新對象 obj 是使用 new 操做符後跟一個構造函數來建立的。構造函數(Object)自己就是一個函數(就是上面說的函數對象),它和上面的構造函數 Person 差很少。只不過該函數是出於建立新對象的目的而定義的。因此不要被 Object 嚇倒。
同理,能夠建立對象的構造器不只僅有 Object,也能夠是 Array,Date,Function等。
因此咱們也能夠構造函數來建立 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;
這些構造器都是函數對象:
小測試來檢驗一下你理解的怎麼樣:
person1.__proto__
是什麼?Person.__proto__
是什麼?Person.prototype.__proto__
是什麼?Object.__proto__
是什麼?Object.prototype__proto__
是什麼?答案:
第一題:
由於 person1.__proto__ === person1 的構造函數.prototype
由於 person1的構造函數 === Person
因此 person1.__proto__ === Person.prototype
第二題:
由於 Person.__proto__ === Person的構造函數.prototype
由於 Person的構造函數 === Function
因此 Person.__proto__ === Function.prototype
第三題:
Person.prototype
是一個普通對象,咱們無需關注它有哪些屬性,只要記住它是一個普通對象。
由於一個普通對象的構造函數 === Object
因此 Person.prototype.__proto__ === Object.prototype
第四題,參照第二題,由於 Person 和 Object 同樣都是構造函數
第五題:
Object.prototype
對象也有proto屬性,但它比較特殊,爲 null 。由於 null 處於原型鏈的頂端,這個只能記住。
Object.prototype.__proto__ === null
全部函數對象的proto都指向Function.prototype,它是一個空函數(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僅在函數調用時由JS引擎建立,Math,JSON是以對象形式存在的,無需new。它們的proto是Object.prototype。以下
Math.__proto__ === Object.prototype // true Math.construrctor == Object // true JSON.__proto__ === Object.prototype // true JSON.construrctor == Object //true
上面說的函數對象固然包括自定義的。以下
// 函數聲明 function Person() {} // 函數表達式 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
噢,上面還提到它是一個空的函數,console.log(Function.prototype)
下看看(留意,下一節會再說一下這個)
知道了全部構造器(含內置及自定義)的__proto__
都是Function.prototype
,那Function.prototype
的__proto__
是誰呢?
相信都據說過JavaScript中函數也是一等公民,那從哪能體現呢?以下
console.log(Function.prototype.__proto__ === Object.prototype) // true
這說明全部的構造器也都是一個普通 JS 對象,能夠給構造器添加/刪除屬性等。同時它也繼承了Object.prototype上的全部方法:toString、valueOf、hasOwnProperty等。(你也應該明白第一句話,第二句話咱們下一節繼續說,不用挖坑了,仍是剛纔那個坑;))
最後Object.prototype的proto是誰?
Object.prototype.__proto__ === null // true
已經到頂了,爲null。(讀到如今,再回過頭看第五章,能明白嗎?)
在 ECMAScript 核心所定義的所有屬性中,最回味無窮的就要數
prototype
屬性了。對於 ECMAScript 中的引用類型而言,prototype
是保存着它們全部實例方法的真正所在。換句話所說,諸如toString()
和valuseOf()
等方法實際上都保存在prototype
名下,只不過是經過各自對象的實例訪問罷了。
——《JavaScript 高級程序設計》第三版 P116
咱們知道 JS 內置了一些方法供咱們使用,好比:
對象能夠用 constructor/toString()/valueOf()
等方法;
數組能夠用 map()/filter()/reducer()
等方法;
數字可用用 parseInt()/parseFloat()
等方法;
var Person = new Object()
Person
是 Object
的實例,因此 Person
繼承了Object
的原型對象Object.prototype
上全部的方法:
Object 的每一個實例都具備以上的屬性和方法。
因此我能夠用 Person.constructor
也能夠用 Person.hasOwnProperty
。
var num = new Array()
num
是 Array
的實例,因此 num
繼承了Array
的原型對象Array.prototype
上全部的方法:
Are you f***ing kidding me? 這尼瑪怎麼是一個空數組???
咱們能夠用一個 ES5 提供的新方法:Object.getOwnPropertyNames
獲取全部(包括不可枚舉的屬性)的屬性名不包括 prototy
中的屬性,返回一個數組:
var arrayAllKeys = Array.prototype; // [] 空數組 // 只獲得 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"] */
這樣你就明白了隨便聲明一個數組,它爲啥能用那麼多方法了。
細心的你確定發現了Object.getOwnPropertyNames(arrayAllKeys)
輸出的數組裏並無 constructor/hasOwnPrototype
等對象的方法(你確定沒發現)。
可是隨便定義的數組也能用這些方法
var num = [1]; console.log(num.hasOwnPrototype()) // false (輸出布爾值而不是報錯)
由於Array.prototype
雖然沒這些方法,可是它有原型對象(__proto__
):
// 上面咱們說了 Object.prototype 就是一個普通對象。 Array.prototype.__proto__ == Object.prototype
因此 Array.prototype
繼承了對象的全部方法,當你用num.hasOwnPrototype()
時,JS 會先查一下它的構造函數 (Array
) 的原型對象 Array.prototype
有沒有有hasOwnPrototype()
方法,沒查到的話繼續查一下 Array.prototype
的原型對象 Array.prototype.__proto__
有沒有這個方法。
var f = new Function("x","return x*x;"); //固然你也能夠這麼建立 f = function(x){ return x*x } console.log(f.arguments) // arguments 方法從哪裏來的? console.log(f.call(window)) // call 方法從哪裏來的? console.log(Function.prototype) // function() {} (一個空的函數) console.log(Object.getOwnPropertyNames(Function.prototype)); /* 輸出 ["length", "name", "arguments", "caller", "constructor", "bind", "toString", "call", "apply"] */
咱們再複習第八小節這句話:
全部函數對象proto都指向
Function.prototype
,它是一個空函數(Empty function)
嗯,咱們驗證了它就是空函數。不過不要忽略前半句。咱們枚舉出了它的全部的方法,因此全部的函數對象都能用,好比:
而後能夠再複習下爲何:
Function.prototype
是惟一一個typeof XXX.prototype爲 「function」的prototype
第八小節咱們總結了:
全部函數對象的 __proto__ 都指向 Function.prototype,它是一個空函數(Empty function)
全部對象的 __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(){} (空函數) var num = new Array() console.log(num.__proto__ == Array.prototype) // true console.log( Array.prototype.__proto__ == Object.prototype) // true console.log(Array.prototype) // [] (空數組) console.log(Object.prototype.__proto__) //null console.log(Array.__proto__ == Function.prototype)// true
疑點解惑:
Object.__proto__ === Function.prototype // true
Object
是函數對象,是經過new Function()
建立的,因此Object.__proto__
指向Function.prototype
。(參照第八小節:「全部函數對象的__proto__
都指向Function.prototype
」)
Function.__proto__ === Function.prototype // true
Function
也是對象函數,也是經過new Function()
建立,因此Function.__proto__
指向Function.prototype
。
本身是由本身建立的,好像不符合邏輯,但仔細想一想,現實世界也有些相似,你是怎麼來的,你媽生的,你媽怎麼來的,你姥姥生的,……類人猿進化來的,那類人猿從哪來,一直追溯下去……,就是無,(NULL生萬物)
正如《道德經》裏所說「無,名天地之始」。
Function.prototype.__proto__ === Object.prototype //true
其實這一點我也有點困惑,不過也能夠試着解釋一下。
Function.prototype
是個函數對象,理論上他的__proto__
應該指向Function.prototype
,就是他本身,本身指向本身,沒有意義。
JS一直強調萬物皆對象,函數對象也是對象,給他認個祖宗,指向Object.prototype
。Object.prototype.__proto__ === null
,保證原型鏈可以正常結束。
__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
)與構造函數的原型對象(dog.prototype
)之間,而不是存在於實例(tidy
)與構造函數(dog
)之間。
聰明的你確定想通了吧 :)