
這篇筆記延伸上一篇所提到的原型(prototype)的概念,說明了在 JavaScript 當中,所有的東西(字串、數值、布林值、函式、陣列、物件)的 prototype 的最後都是物件!
什麼意思呢?
假設我們現在分別建立物件、函式和陣列:
// Object var a = { name:'pjchender' } // function var b = function(){ console.log('Hello'); } // Array var c = ['this','is','an','array']; // string var d = 'This is string'; // number var e = 3; // boolean var f = false;
接著,我們會在 Google Chrome 的 console 視窗來分別檢視這些變數的 prototype。
物件(object)
我們可以看到 a 這個物件本身的 prototype 也是一個物件,在下去就沒了(null),也就是 Object → Object → null。

而 a.__proto__ 就是物件的原型,打開來看會發現裡面有許多內建的方法。

如果我在 console 中輸入 a.,則會出現對於物件而言內建的方法:

由於 a.__proto__ 仍然是一個物件,所以如果我輸入 a.__proto__.的話,會得到一樣對於物件可以使用的方法:

函式(function)
接著我們來看看函式,它會是 function → function → object → null,所以最後還是結束在 object。

如果我們想要看函式有哪些內建的方法可以用,我們可以輸入 b. 或 b.__proto__. 就可以看到了,這裡我們就可以看到我們之前使用的 apply, bind, 和 call。

陣列(Array)
再來陣列的話則是 array → array → object → null。

如果我們要看陣列有哪些方法可以用,一樣可以透過 c. 或 c.__proto__. 來檢視:

同樣的方法也可以用來檢視字串、數字和布林值,透過 chrome 來試試看吧!
0 意見:
張貼留言