2016-11-22 59 views
0

這是我無法弄清的一個技巧問題。當我從MDN讀取時,我們無法從Math創建實例。運行new Math()將產生一個例外Math is not a constructor。但數學在Math.constructor內有自己的財產。是的,它是Object類型,但我們可以運行它Math.constructor()。但即使我們通過exec Math.constructor = Function.constructor重新定義它也會拋出異常。數學不是一個構造函數,但它有

現在,我已經在我心中的若干構想:

  • 構造包含一個隱藏屬性和瀏覽器引擎拒絕調用它。
  • 構造函數在「TypeError:not a constructor」集合中具有索引的瀏覽器引擎中解釋爲特殊的C++對象。

有人可以回答我爲什麼構造函數存在,但我不能創建一個實例嗎?

在此先感謝。

+5

每個對象都有一個構造函數,並不意味着你可以創建對象文字的新實例等。這個問題的答案可能只是*「,因爲規範說是這樣」*。 – adeneo

+0

@AndreiZhamoida [你可以隨時閱讀語言規範:]](http://www.ecma-international.org/ecma-262/6.0/) – Pointy

+0

'Math'是一個對象。這個對象必須被構造。每個對象*繼承它的構造函數的原型方法(在這種情況下爲Object)。 'Object.prototype.constructor = Object' – Thomas

回答

2

要引用自己,答案是

because the spec says so

spec says

The Math Object

The Math object is a single object that has some named properties, some of which are functions.

The value of the [[Prototype]] internal property of the Math object is the standard built-in Object prototype object (15.2.4). The value of the [[Class]] internal property of the Math object is "Math".

The Math object does not have a [[Construct]] internal property; it is not possible to use the Math object as a constructor with the new operator.

The Math object does not have a [[Call]] internal property; it is not possible to invoke the Math object as a function.

在javascript每個對象都有一個構造函數,Math是一個對象,因此它有一個構造函數,那並不這意味着你可以創建它的新實例,它與

var Math = { 
 
    random : true, 
 
    max : false 
 
} 
 

 
new Math(); // epic fail, not a constructor (function)

+0

嗯,我認爲這絕對是我一直在尋找的東西。我可以說根據規範隱藏在瀏覽器引擎實現中的是什麼?它會糾正嗎? –

+0

@AndreiZhamoida - 當然,就是這樣? – adeneo

+0

Yeees,謝謝,+接受))。 –

相關問題