最詳盡的 JS 原型與原型鏈終極詳解(三)
小編推薦:Fundebug專注於JavaScript、微信小程式、微信小遊戲,Node.js和Java實時BUG監控。真的是一個很好用的bug監控費服務,眾多大佬公司都在使用。
七. 函式物件 (複習一下前面的知識點)
所有函式物件的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 ???
why??
當我們建立一個函式時:
var Person = new Object()
Person
是 Object
的例項,所以 Person
繼承了Object
的原型物件Object.prototype
上所有的方法:
Object.prototype
Object 的每個例項都具有以上的屬性和方法。
所以我可以用 Person.constructor
也可以用 Person.hasOwnProperty
。
當我們建立一個數組時:
var num = new Array()
num
是 Array
的例項,所以 num
繼承了Array
的原型物件Array.prototype
上所有的方法:
Array.prototype
Are you f***ing kidding me? 這尼瑪怎麼是一個空陣列???
doge
我們可以用一個 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 ???
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)
嗯,我們驗證了它就是空函式。不過不要忽略前半句。我們枚舉出了它的所有的方法,所以所有的函式物件都能用,比如:
函式物件
如果你還沒搞懂啥是函式物件?
去屎 | center
還有,我建議你可以再複習下為什麼:
Function.prototype
是唯一一個typeof XXX.prototype為 “function”的prototype
我猜你肯定忘了。
九. 複習一下
第八小節我們總結了:
所有函式物件的 __proto__ 都指向 Function.prototype,它是一個空函式(Empty function)
但是你可別忘了在第三小節我們總結的:
所有物件的 __proto__ 都指向其構造器的 prototype
咦,我找了半天怎麼沒找到這句話……
doge | center
我們下面再複習下這句話。
先看看 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
)之間。
聰明的你肯定想通了吧 :)
作者:Yi罐可樂
連結:https://www.jianshu.com/p/a4e1e7b6f4f8
關於Fundebug
Fundebug專注於JavaScript、微信小程式、微信小遊戲、支付寶小程式、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了9億+錯誤事件,得到了Google、360、金山軟體、百姓網等眾多知名使用者的認可。歡迎免費試用!