2012-01-01 81 views
10

這裏是JavaScript的以下問題:爲什麼「foo」.toString()與toString.call(「foo」)不一樣?

// Tested via Google Chrome console. 
var toString = Object.prototype.toString; 

"foo".toString(); // "foo" 
toString.call("foo"); // [object String] 

[].toString(); // "" 
toString.call([]); // [object Array] 

{}.toString(); // syntax error 
toString.call({}); // [object Object] 

爲什麼的toString的結果是不同與toString.call()?

修訂

String.prototype.toString.call("foo"); // "foo" 
Object.prototype.toString.call("foo"); // [object String] 

是String.prototype.toString不是從原型鏈像下面?

的toString字符串[未找到] - > [未找到]在String.prototype的toString

      --> toString in Object.prototype[found] 
+0

不是一個JavaScript專家,但我懷疑它與調用預定義的函數,並傳遞一個null參數,而不是做在一個不存在的對象上調用一個函數。 – bdares 2012-01-01 11:55:27

+0

你如何檢查這些結果?瀏覽器控制檯,還是別的? – 2012-01-01 11:55:50

+0

@ShadowWizard Chrome瀏覽器控制檯。 – 2012-01-01 12:02:26

回答

16

String.prototype.toString優先Object.prototype.toString。它們不是同一個功能。

specification of String.prototype.toString

返回此字符串值。 (需要注意的是,對於一個String對象,該的toString方法恰好返回同樣的事情的valueOf方法。)

而且Object.prototype.toString

的toString方法所謂,採取以下步驟:

  1. Ø是調用ToObject傳遞這個值作爲參數的結果。
  2. 類別的[[Class]]內部屬性的值。
  3. 返回字符串值,該值是串接三個字符串的結果「[對象,和「]」。

陣列的行爲相似,而且還覆蓋toString()

> [1,2].toString() 
    "1,2" 
4
>>> String.prototype.toString.call("foo") 
"foo" 

對象不是一回事爲一個字符串。

+0

String的** toString **方法來自「String .__ proto__」嗎?而'String .__ proto__'應該是'Object',那麼爲什麼String中的** toString **不等於Object中的** toString **? – 2012-01-01 12:16:14

+1

是的,但String重寫Object toString以顯示比[Object X]更友好的打印輸出。如果它沒有覆蓋默認的toString,你的想法就是對的。 – 2012-01-01 12:19:57

-1

全局toString函數與object.toString()函數不同。 根據this source,全局的toString函數沒有很好的定義,因此在不同瀏覽器中實現的效果很差。本質上它提供了與typeof操作員相似的功能。

+0

toString OP引用的不是沒有明確定義的「全局toString」,而是由OP – 2012-01-01 12:26:47

+0

定義爲「var toString = Object.prototype.toString」,我的眼睛必須經過第一行代碼。道歉。 – Jivings 2012-01-01 12:32:27

相關問題