I found interesting output when I set this
to a string using apply
and then console.log
'd it. What's up?
In Chrome's Javascript console,
(function(){ return this }).apply("hello");
Outputs to:
String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}
Why isn't it "hello"
like I would have expected?
Interestingly, checking this output with typeof
:
typeof (function(){ return this }).apply("hello");
Gives me "object"
, instead of "string"
.
I'm guessing that is some wizardry with apply
that I don't understand?
When the argument for this
is passed in non-strict mode, it is converted to an object, so it's returning a string object, which is different from a string value. Each index in a string object corresponds to the characters of a string value, in order. To convert it back to a "normal" string, just call toString()
on it - that makes it a string value like you're used to.
This does not occur in ES5 strict mode (when you insert 'use strict'
at the beginning of your program or function), as in that mode arguments are not coerced to objects, but given directly.
// if you're not passing any arguments, it doesn't matter whether you use apply or call
(function () { return this; }).call("see"); // { 0: "s", 1: "e", 2: "e" }, plus some other special properties
(function () { return this.toString(); }).call("see"); // "see"
(function () { 'use strict'; return this; }).call("see"); // "see", where strict mode is supported
Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3 (note that the ThisBinding
refers to the value of the this
keyword inside the function).
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