七. 函數(shù)對象 (復(fù)習(xí)一下前面的知識點(diǎn))
所有函數(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
// 所有的構(gòu)造器都來自于Function.prototype,甚至包括根構(gòu)造器Object及Function自身
Object.__proto__ === Function.prototype // true
Object.constructor == Function // true
// 所有的構(gòu)造器都來自于Function.prototype,甚至包括根構(gòu)造器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中有內(nèi)置(build-in)構(gòu)造器/對象共計(jì)12個(ES5中新加了JSON),這里列舉了可訪問的8個構(gòu)造器。剩下如Global不能直接訪問,Arguments僅在函數(shù)調(diào)用時(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ù)對象當(dāng)然包括自定義的。如下
// 函數(shù)聲明
function Person() {}
// 函數(shù)表達(dá)式
var Perosn = function() {}
console.log(Person.__proto__ === Function.prototype) // true
console.log(Man.__proto__ === Function.prototype) // true
這說明什么呢?
** 所有的構(gòu)造器都來自于 Function.prototype,甚至包括根構(gòu)造器Object及Function自身。所有構(gòu)造器都繼承了·Function.prototype·的屬性及方法。如length、call、apply、bind**
(你應(yīng)該明白第一句話,第二句話我們下一節(jié)繼續(xù)說,先挖個坑:))
Function.prototype也是唯一一個typeof XXX.prototype為 function的prototype。其它的構(gòu)造器的prototype都是一個對象(原因第三節(jié)里已經(jīng)解釋過了)。如下(又復(fù)習(xí)了一遍):
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) 下看看(留意,下一節(jié)會再說一下這個)
知道了所有構(gòu)造器(含內(nèi)置及自定義)的__proto__都是Function.prototype,那Function.prototype的__proto__是誰呢?
相信都聽說過JavaScript中函數(shù)也是一等公民,那從哪能體現(xiàn)呢?如下
console.log(Function.prototype.__proto__ === Object.prototype) // true
這說明所有的構(gòu)造器也都是一個普通 JS 對象,可以給構(gòu)造器添加/刪除屬性等。同時(shí)它也繼承了Object.prototype上的所有方法:toString、valueOf、hasOwnProperty等。(你也應(yīng)該明白第一句話,第二句話我們下一節(jié)繼續(xù)說,不用挖坑了,還是剛才那個坑;))
最后Object.prototype的proto是誰?
Object.prototype.__proto__ === null // true
已經(jīng)到頂了,為null。(讀到現(xiàn)在,再回過頭看第五章,能明白嗎?)
八. Prototype
在 ECMAScript 核心所定義的全部屬性中,最耐人尋味的就要數(shù)
prototype屬性了。對于 ECMAScript 中的引用類型而言,prototype是保存著它們所有實(shí)例方法的真正所在。換句話所說,諸如toString()和valuseOf()等方法實(shí)際上都保存在prototype名下,只不過是通過各自對象的實(shí)例訪問罷了。
——《JavaScript 高級程序設(shè)計(jì)》第三版 P116
我們知道 JS 內(nèi)置了一些方法供我們使用,比如:
對象可以用 constructor/toString()/valueOf() 等方法;
數(shù)組可以用 map()/filter()/reducer() 等方法;
數(shù)字可用用 parseInt()/parseFloat()等方法;
Why ???

當(dāng)我們創(chuàng)建一個函數(shù)時(shí):
var Person = new Object()
Person 是 Object 的實(shí)例,所以 Person 繼承了Object 的原型對象Object.prototype上所有的方法:

Object 的每個實(shí)例都具有以上的屬性和方法。
所以我可以用
Person.constructor 也可以用 Person.hasOwnProperty。
當(dāng)我們創(chuàng)建一個數(shù)組時(shí):
var num = new Array()
num 是 Array 的實(shí)例,所以 num 繼承了Array 的原型對象Array.prototype上所有的方法:

Are you f***ing kidding me? 這尼瑪怎么是一個空數(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ù)組,它為啥能用那么多方法了。
細(xì)心的你肯定發(fā)現(xiàn)了Object.getOwnPropertyNames(arrayAllKeys) 輸出的數(shù)組里并沒有 constructor/hasOwnPrototype等對象的方法(你肯定沒發(fā)現(xiàn))。
但是隨便定義的數(shù)組也能用這些方法
var num = [1];
console.log(num.hasOwnPrototype()) // false (輸出布爾值而不是報(bào)錯)
Why ???

因?yàn)?code>Array.prototype 雖然沒這些方法,但是它有原型對象(__proto__):
// 上面我們說了 Object.prototype 就是一個普通對象。
Array.prototype.__proto__ == Object.prototype
所以 Array.prototype 繼承了對象的所有方法,當(dāng)你用num.hasOwnPrototype()時(shí),JS 會先查一下它的構(gòu)造函數(shù) (Array) 的原型對象 Array.prototype 有沒有有hasOwnPrototype()方法,沒查到的話繼續(xù)查一下 Array.prototype 的原型對象 Array.prototype.__proto__有沒有這個方法。
當(dāng)我們創(chuàng)建一個函數(shù)時(shí):
var f = new Function("x","return x*x;");
//當(dāng)然你也可以這么創(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"]
*/
我們再復(fù)習(xí)第八小節(jié)這句話:
所有函數(shù)對象proto都指向
Function.prototype,它是一個空函數(shù)(Empty function)
嗯,我們驗(yàn)證了它就是空函數(shù)。不過不要忽略前半句。我們枚舉出了它的所有的方法,所以所有的函數(shù)對象都能用,比如:

如果你還沒搞懂啥是函數(shù)對象?

還有,我建議你可以再復(fù)習(xí)下為什么:
Function.prototype是唯一一個typeof XXX.prototype為 “function”的prototype
我猜你肯定忘了。
九. 復(fù)習(xí)一下
第八小節(jié)我們總結(jié)了:
所有函數(shù)對象的 __proto__ 都指向 Function.prototype,它是一個空函數(shù)(Empty function)
但是你可別忘了在第三小節(jié)我們總結(jié)的:
所有對象的 __proto__ 都指向其構(gòu)造器的 prototype
咦,我找了半天怎么沒找到這句話……

我們下面再復(fù)習(xí)下這句話。
先看看 JS 內(nèi)置構(gòu)造器:
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
再看看自定義的構(gòu)造器,這里定義了一個 Person:
function Person(name) {
this.name = name;
}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true
p 是 Person 的實(shí)例對象,p 的內(nèi)部原型總是指向其構(gòu)造器 Person 的原型對象 prototype。
每個對象都有一個 constructor 屬性,可以獲取它的構(gòu)造器,因此以下打印結(jié)果也是恒等的:
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都是恒等的,即都指向同一個對象。
如果換一種方式設(shè)置原型,結(jié)果就有些不同了:
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(注意:上一個示例是修改原型)。輸出結(jié)果可以看出p.__proto__仍然指向的是Person.prototype,而不是p.constructor.prototype。
這也很好理解,給Person.prototype賦值的是一個對象直接量{getName: function(){}},使用對象直接量方式定義的對象其構(gòu)造器(constructor)指向的是根構(gòu)造器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ˇ?)
十. 原型鏈(再復(fù)習(xí)一下:)
下面這個例子你應(yīng)該能明白了!
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
疑點(diǎn)解惑:
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)建的,好像不符合邏輯,但仔細(xì)想想,現(xiàn)實(shí)世界也有些類似,你是怎么來的,你媽生的,你媽怎么來的,你姥姥生的,……類人猿進(jìn)化來的,那類人猿從哪來,一直追溯下去……,就是無,(NULL生萬物)
正如《道德經(jīng)》里所說“無,名天地之始”。
Function.prototype.__proto__ === Object.prototype //true
其實(shí)這一點(diǎn)我也有點(diǎn)困惑,不過也可以試著解釋一下。
Function.prototype是個函數(shù)對象,理論上他的__proto__應(yīng)該指向Function.prototype,就是他自己,自己指向自己,沒有意義。
JS一直強(qiáng)調(diào)萬物皆對象,函數(shù)對象也是對象,給他認(rèn)個祖宗,指向Object.prototype。Object.prototype.__proto__ === null,保證原型鏈能夠正常結(jié)束。
十一 總結(jié)
- 原型和原型鏈?zhǔn)荍S實(shí)現(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
這個明白吧?想一想我們上面說過這句話:
實(shí)例(
tidy)和 原型對象(dog.prototype)存在一個連接。不過,要明確的真正重要的一點(diǎn)就是,這個連接存在于實(shí)例(tidy)與構(gòu)造函數(shù)的原型對象(dog.prototype)之間,而不是存在于實(shí)例(tidy)與構(gòu)造函數(shù)(dog)之間。
聰明的你肯定想通了吧 :)
本文借鑒了:
-
《JS原型與原型鏈終極詳解》
作者:zhangjiahao8961 -
JavaScript中proto與prototype的關(guān)系
作者:snandy - 《JavaScript 高級程序設(shè)計(jì)》中文譯本 第三版