你能想到的Object.prototype.toString
(或簡化版本),因爲這:
Object.prototype.toString = function() {
var myType = (typeof this)[0].toUpperCase() + (typeof this).substr(1);
return "[Object " + myType + "]";
}
(無關:見注,答案是什麼(typeof運算本)[0]不解釋的底部,但假設對於現在的myType =「字符串」的字符串,「陣列」用於陣列等),因爲由於
和它的從[].toString()
不同的陣列是一個對象的只是一個孩子,toString
爲陣列只是覆蓋:
Array.prototype.toString = function() {
return this.join(',');
}
當您撥打Object.prototype.toString
您指的是第一個功能,[].toString
指的是第二個。這是沒有什麼不同,如果你這樣做:
function MyClass() {};
var x = new MyClass;
x.toString(); // prints "[object Object]"
MyClass.prototype.toString = function() { return 'hello!' }
x.toString(); // prints "hello!"
// and we can call Object's toString method instead
Object.prototype.toString.call(x); // prints "[object Object]"
第一次調用調用Object.prototype.toString
因爲MyClass
是Object
子類,並沒有自己的toString
方法。然後當我們給MyClass
a toString
方法時,調用x.toString
在MyClass
上使用toString
方法,最後我們可以再次調用我們的「超類」toString
方法Object.prototype.toString.call(x)
。
這是什麼(typeof this)[0]做的?(typeof this)
返回你的班級的名字。 typeof ""
返回"string"
,typeof 5
返回"number"
等(注意,數組實際上有object
,但[] instanceof Array
是真的!)。但是這總是小寫的。 Object.prototype.toString
返回一個字符串,如"Object String"
,其中對象的類型是大寫。 (typeof this)[0]
說「給我的字符串的第一個字符」和(typeof this).substr(1)
說「給我的字符串的第一個字符」「以外的每個字符。同樣,這裏的字符串(typeof this)
只是對象的小寫表示。呼叫toUpperCase
確保第一個字符大寫。
嗨!在這裏這行:var myType =(typeof this)[0] .toUpperCase()+(typeof this).substr(1);爲什麼你在[typeof this]之後有[0]?你可以走過變量myType將是什麼?像什麼將(打印此)[0] .toUpperCase()打印出來?陣列?和(typeof this).substr(1)。謝謝! – LP496
當然,(typeof this)會返回你班級的名字。 typeof「」返回字符串,typeof []返回數組等。但是這總是小寫。 Object.prototype.toString返回一個字符串,比如「Object String」,其中對象的類型是大寫。 (typeof this)[0]說:「給我字符串的第一個字符,並且(typeof this).substr(1)說」給我字符串的第一個字符之外的所有字符「。這個)只是對象的小寫形式,toUpperCase調用確保第一個字符大寫 – Macmee
Ohh ok!我不知道你可以使用[0]訪問字符串中的字符,所以在這種情況下( typeof這個)會返回一個小寫的數組a,並且你訪問一個並且使它成爲大寫。 – LP496