vybacq
Last Updated: February 25, 2016
·
1.057K
· coreygrunewald

Using .apply with Strings in JavaScript

Ran into an interesting issue with trying to pass a primitive String variable in as the context during an .apply call. The String primitive was autoboxed to a String object.

Here is an example of this happening:

function boxing() { return this; }

var test = 'test';

boxing.apply(test) === 'test'; // will return false

When the test variable gets passed in as the context using the apply function, it gets boxed to the actual String object, not the primitive.

The way to have this autoboxing not occur, is to put the:

use strict;

declaration at the top of your file. This will prevent the vm from autoboxing the context in the .apply function.

3 Responses
Add your response

5242

But what is the actual problem that you face as a result of "auto boxing" in this case?

over 1 year ago ·
5243

As you can see, inequality issues can arise. This boxing issue occurs for any primitive.

over 1 year ago ·
5245

Yes but when in real world would you pass a string as "this" reference to a function?

over 1 year ago ·