2014-10-28 61 views
0

換句話說,第一個是什麼?一個雞蛋還是一隻母雞?我無法理解JavaScript是如何實現的,因爲我讀了這個:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#Properties_and_Methods_of_Function在JavaScript中:如果Object是一個函數,那麼如果一個函數是一個對象的實例,它怎麼會是這樣呢

正如你在控制檯中看到:

>Object instanceof Function 
true 
>new Function() instanceof Object 
true 

似乎是一個致命的循環。

爲什麼所有這些:

typeof new Object() 
typeof new Array() 
typeof new Date() 
typeof new RegExp() 
typeof new Number() 
typeof new Boolean() 
typeof new String() 

回報 「對象」,但這:

typeof new Function() 

返回 「功能」

好像什麼...是Object源自功能? 我不這麼認爲,因爲:

>new Function() instanceof Object 
true 
>new Object() instanceof Function 
false 

所以不...

+1

'Object' *是一個也是一個對象的函數,'new'創建一個對象,它可以是一個函數。 – elclanrs 2014-10-28 01:29:48

+1

[爲什麼在JavaScript中,「Object instanceof Function」和「Function instanceof Object」返回true?](http://stackoverflow.com/questions/23622695/why-in-javascript-both-object-instanceoffunction -and-function-instanceof-obj)和[Object and Function相當混亂](http:// stackoverflow。com/questions/2003183/object-and-function-are-quite-confusing) – 2014-10-28 02:26:13

+0

'object'是一個類型; 「對象」是一個函數和對象(所有函數都是對象); 'Object'是一個可以構造'Object'類型的對象的類,它們是Object類的實例。所有其他類都從基類「Object」繼承。所以'new Function()'的實例就是函數,它們是基類爲Object的'Function'類的實例的對象。所以一個函數(或者一個函數類型的對象)既是一個函數又是一個對象。清晰如泥,對吧? – nothingisnecessary 2014-10-28 02:57:38

回答

2

它看起來像你得到的類型,功能和對象的困惑。

簡短的回答:

在Javascript中函數是對象。對象不是函數,但存在創建和/或返回對象的函數。

詳細的解答舉例:

你是正確的函數是對象。 Object是一個功能,所以Function如下面的控制檯輸出所示。

但是當你說Object是一個函數時,你實際上是在談論Object()函數,而不是object類型。

// Object is a function 
> Object 
function Object() { [native code] } 

// Function is a function 
> Function 
function Function() { [native code] } 

// The type of Object is function 
> typeof(Object) 
"function" 

// The type of the result of invoking the Object() function (AKA constructor, since using "new" keyword) is a new object 
> typeof(new Object()) 
"object" 

> new Object() instanceof Object 
true 
> new Function() instanceof Function 
true 
// note the difference 
> new Object() instanceof Function 
false 
> new Function() instanceof Object 
true 

在您的例子在某些情況下,你實際上是在調用該函數並查看函數的結果,而不是函數本身。例如,typeof(String) === "function"typeof(new String()) === "object"(在這種情況下爲「String」對象)。

當您使用new關鍵字調用這些函數時,您將得到一個新對象,其類是您調用的函數的名稱。 new Function() instanceof Object === true的原因是Object是以這種方式構建的任何對象的基類。 Object是基類的名稱,實例的類型是"object"(即從類創建的對象,如來自cookie切割器的cookie)。

相關問題