Guid
Guid

Reputation: 2216

Use a string as a function call scope

function foobar() {
    console.log(this);
}

foobar.call("Hello");

This code displays :

{ '0': 'H', '1': 'e', '2': 'l', '3': 'l', '4': 'o' }

I was expecting "Hello" to be displayed.

Why? and how to remedy this?

Upvotes: 0

Views: 38

Answers (2)

Quentin
Quentin

Reputation: 944202

Function#call is (indirectly) converting the string primitive into a String object (see §10.4.3 of the spec; we get there starting from §15.3.4.4, which takes us to §13.2.1, which takes us to §10.4.3).

You can force it back with:

console.log(this.toString());

Note that in strict mode, it wouldn't be converted to a String object, because in strict mode, this can be a primitive (including a primitive string). E.g.:

// Here, it gets converted to an object
function foo() {
  snippet.log(typeof this); // "object"
}
foo.call("Hello");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

But if we use strict mode:

// Strict mode
"use strict";

// Here, it remains a primitive
function foo() {
  snippet.log(typeof this); // "string"
}
foo.call("Hello");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 3

zavg
zavg

Reputation: 11071

Since the first argument thisArg of call() function is not null or undefined so the value of this inside function body equals to Object(thisArg).

Look more in call function description.

Upvotes: 2

Related Questions