Reputation: 5337
Here's something I found in some code I was reading, when I tested in the console:
Object.prototype.toString("foo"); // output: "[object Object]" Object.prototype.toString.call("foo"); // output: "[object String]"
I think I may have a faint idea but I can't express in words... can anyone explain?
Upvotes: 1
Views: 92
Reputation: 18584
The two calls are NOT equivalent.
The first call:
Object.prototype.toString("foo");
calls the toString
method in the context of Object.prototype
, with an additional "foo"
parameter (unused), and Object.prototype
is an Object
, so the result is [object Object]
The second call:
Object.prototype.toString.call("foo");
calls the toString
method in the context of "foo"
, and Object.prototype.toString
builds an object from it (new String("foo")
), so the result is [object String]
Upvotes: 4
Reputation: 27823
The first parameter of call
is the object that will be this
inside the function, not the first parameter of the function:
"use strict";
function test(a,b) {
console.log(this, a, b);
};
var obj = {
'func' : test
}
test(1,2) // outputs undefined 1 2
test.call(1,2); // outputs 1 2 undefined
obj.func(1,2) // outputs obj 1 2
obj.func.call(1,2) // outputs 1 2 undefined
Upvotes: 0