![](/img/trans.png)
[英]Why are .call and .apply slower than a direct function call in JavaScript?
[英]Why in javascript apply gives different result than direct call?
我有以下代碼
var d = new Date();
Object.prototype.toString(d); //outputs "[object Object]"
Object.prototype.toString.apply(d); //outputs "[object Date]"
為什么會出現這種差異以及發生了什么?
編輯:
d.toString() // outputs "Tue Nov 06 2012 ..."
那么“[對象日期]”中的日期來自何處。 它是瀏覽器的本機代碼嗎?
Object.prototype.toString(d);
將Object.prototype
轉換為string並忽略其參數。 在
Object.prototype.ToString.apply(d);
d
被作為傳遞this
給ToString
方法(好像d.toString()
用toString
指Object.prototype.toString
被稱為),這是什么方法方面。
在第一次調用中忽略該參數。 您正在調用Object.prototype
對象上的toString
方法,基本上與:
{}.toString(); //outputs "[object Object]"
在第二個調用中,您正在為Object
調用toString
方法,但將Date
對象應用為其上下文。 該方法返回該對象為字符串的類型,相比較toString
所述的方法Date
對象這將代替返回的值Date
對象為字符串。
另一種解釋是, Object.prototype.toString
其上運行this
對象。 函數的this
由你怎么稱呼它,當你設置:
Object.prototype.toString();
toString
函數this
是Object.prototype
對象。 當你把它稱為:
Object.prototype.toString.apply(d);
其this
是由所引用的對象d
(Date對象)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.