七. 函數對象 (復習一下前面的知識點)
所有函數對象的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。(讀到現在,再回過頭看第五章,能明白嗎?)
八. Prototype
在 ECMAScript 核心所定義的全部屬性中,最耐人尋味的就要數
prototype
屬性了。對于 ECMAScript 中的引用類型而言,prototype
是保存著它們所有實例方法的真正所在。換句話所說,諸如toString()
和valuseOf()
等方法實際上都保存在prototype
名下,只不過是通過各自對象的實例訪問罷了。
——《JavaScript 高級程序設計》第三版 P116
我們知道 JS 內置了一些方法供我們使用,比如:
對象可以用 constructor/toString()/valueOf()
等方法;
數組可以用 map()/filter()/reducer()
等方法;
數字可用用 parseInt()/parseFloat()
等方法;
Why ???
當我們創建一個函數時:
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 (輸出布爾值而不是報錯)
Why ???
因為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
,保證原型鏈能夠正常結束。
十一 總結
- 原型和原型鏈是JS實現繼承的一種模型。
- 原型鏈的形成是真正是靠
__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
)之間。
聰明的你肯定想通了吧 :)
本文借鑒了:
-
《JS原型與原型鏈終極詳解》
作者:zhangjiahao8961 -
JavaScript中proto與prototype的關系
作者:snandy - 《JavaScript 高級程序設計》中文譯本 第三版