If I define a function:
function foo() {
alert(this.x);
}
I can print the function definition by calling the toString method on the foo function.
console.log(foo.toString())
output:
function foo() { alert(this.x); }
If I then run
console.log(Object.prototype.toString.call(foo))
output:
"[object Function]"
It is surprising the me that the output is different. I thought these two forms were equivalent?, i.e. the foo function inherited the toString method from the top level Object and using Object.prototype.toString.call(foo) was just calling toString passing the foo function as the this.
What is the difference between these two forms of invocation?
prototype. toString() returns "[object Type]" , where Type is the object type. If the object has a Symbol. toStringTag property whose value is a string, that value will be used as the Type . Many built-in objects, including Map and Symbol , have a Symbol.
In JavaScript, the Object. prototype. toString() method is used to return a string that can represent the object. The toString() method is automatically inherited by every object which is inherited from Object.
toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.
The toString function for Object (the built-in type for objects) happens to return what type of object it is as a string with the format [object Type]. So for example: const arr = [1,2,3,4,5] Object. prototype. toString. call(arr) // returns "[object Array]" const str = 'test' str.
What is the difference between these two forms of invocation?
It's not just a difference in the form of the invocation, you're also calling a different function entirely.
i.e. the
foofunction inherited thetoStringmethod from the top levelObjectand usingObject.prototype.toString.call(foo)was just callingtoStringpassing thefoofunction as thethis.
All perfect, except the first bit. :-) foo doesn't inherit toString from Object.prototype, because foo is a function, and Function.prototype (which inherits from Object.prototype) overrides toString to give it different behavior.
You can see that like this:
console.log(foo.toString === Object.prototype.toString); // false
It's also entirely possible for foo to have its own toString, overriding the one it inherits from Function.prototype, but by default it doesn't.
So changing just the form of the invocation, we'd get these, which are equivalent:
console.log(foo.toString());
and
console.log(foo.toString.call(foo));
or if we know foo doesn't override Function.prototype's version, then:
console.log(Function.prototype.toString.call(foo));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With