[英]Why in javascript apply gives different result than direct call?
I have the following code 我有以下代码
var d = new Date();
Object.prototype.toString(d); //outputs "[object Object]"
Object.prototype.toString.apply(d); //outputs "[object Date]"
Why is this difference and what's going on? 为什么会出现这种差异以及发生了什么?
edit: 编辑:
d.toString() // outputs "Tue Nov 06 2012 ..."
So from where does the Date in "[object Date]" comes from. 那么“[对象日期]”中的日期来自何处。 Is it the native code of the browser that do the trick? 它是浏览器的本机代码吗?
Object.prototype.toString(d);
converts Object.prototype
to string and ignores its argument. 将Object.prototype
转换为string并忽略其参数。 In 在
Object.prototype.ToString.apply(d);
d
gets passed as this
to the ToString
method (as if d.toString()
with toString
referring to Object.prototype.toString
was called), which is what the method respects. d
被作为传递this
给ToString
方法(好像d.toString()
用toString
指Object.prototype.toString
被称为),这是什么方法方面。
See Function#apply
and Object#toString
请参见Function#apply
和Object#toString
The parameter is ignored in the first call. 在第一次调用中忽略该参数。 You are calling the toString
method on the Object.prototype
object, basically the same as: 您正在调用Object.prototype
对象上的toString
方法,基本上与:
{}.toString(); //outputs "[object Object]"
In the second call you are calling the toString
method for Object
but applying the Date
object as its context. 在第二个调用中,您正在为Object
调用toString
方法,但将Date
对象应用为其上下文。 The method returns the type of the object as a string, compared the toString
method of the Date
object which would instead return the value of the Date
object as a string. 该方法返回该对象为字符串的类型,相比较toString
所述的方法Date
对象这将代替返回的值Date
对象为字符串。
Another explanation is that Object.prototype.toString
operates on its this
object. 另一种解释是, Object.prototype.toString
其上运行this
对象。 A function's this
is set by how you call it so when you do: 函数的this
由你怎么称呼它,当你设置:
Object.prototype.toString();
the toString
function's this
is the Object.prototype
object. toString
函数this
是Object.prototype
对象。 When you call it as: 当你把它称为:
Object.prototype.toString.apply(d);
its this
is the object referenced by d
(a Date object). 其this
是由所引用的对象d
(Date对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.