Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner with Strange Output -- What's going on with strings as 'this'?

Tags:

javascript

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?

like image 377
ChaseMoskal Avatar asked Jan 12 '23 01:01

ChaseMoskal


1 Answers

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).

like image 84
Qantas 94 Heavy Avatar answered Feb 01 '23 22:02

Qantas 94 Heavy