2013-03-27 63 views
6

我在閱讀這本書Javascript:好的部分。我有點困惑,當我讀到下面的代碼:在JavaScript中Number和Function.prototype之間的關係是什麼?

Function.prototype.method = function (name, func) { 
    this.prototype[name] = func; 
    return this; 
}; 

Number.method('integer',function(){ 
    return Math[this < 0 ? 'ceil' : 'floor'](this); 
}); 

我覺得上面的代碼中的第一部分是指在JavaScript中任何函數現在有一個名爲方法方法。但是「數字」也是一個函數嗎?爲什麼Number.method有意義?

我想,Number繼承的Number.prototype繼承Object.prototype(Number-> Number.prototype-> Object.prototype),因爲Number在開始時沒有「method」方法,它會沿着原型鏈。但是Function.prototype不在鏈上,對嗎?

Number,Number.prototype和Function.prototype之間的關係是什麼?


更新我:

我搜索了一些額外的信息和現在比較迷茫。有人說,Number實際上是一個函數,這似乎是有道理的,因爲Number instanceof Function的值是true。但是(-10/3) instanceof Number的值是false。這不是令人困惑嗎?如果數學中的數字(例如3,2.5,( - 10/3))甚至不是JavaScript中的Number,那麼(-10/3)如何調用integer()這是一種來自Number的方法? (下面的線來自同一本書)

document.writeln((-10/3).integer()); 

UPDATE II:

問題解決了,基本上。

感謝@ Xophmeister的幫助,現在我的結論是,Number可以調用method因爲Number是如此,它鏈接到Function.prototype構造。至於爲什麼在JavaScript中基本類型的數字(3,2.5,( - 10/3))可以調用對象Number所具有的方法,則應參考this page

我基本上從@ Xophmeister的幫助和一點搜索得到了這個結論,所以它可能不夠精確。歡迎任何更正或完成。

+0

(-10/3)是一個數字,但不是一個號碼。 – simon 2013-03-27 11:22:39

+0

@simon但是在'Number'中定義了'integer()'方法,對吧?如果(-10/3)不是'Number',爲什麼它可以調用'integer()'? – ChandlerQ 2013-03-27 11:34:48

+0

'-10/3'不是'Number' *對象*,而是* type *'number'。我認爲ECMA262規範的第8.6.2和9.9節與此相關;特別是JS的[[[PrimitiveValue]]和'ToObject'內部。這篇博客文章可能會更好地解釋一些事情:http://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/ – Xophmeister 2013-03-27 12:16:58

回答

3

相信原型鏈是:Object>Function>Number

Number instanceof Function; // true 
Number instanceof Object; // true 
Function instanceof Object; // true 
+0

'Object instanceof Function'也返回'true'。 – 2013-03-27 10:50:40

+0

我猜這是因爲函數是JavaScript中的一等公民。 – Xophmeister 2013-03-27 10:53:19

+0

就像@ neustroev.ai所說的那樣,'Object instanceof Function'是'true'。這是否意味着JavaScript中的所有對象都是一個函數? – ChandlerQ 2013-03-27 11:18:11

相關問題