vybacq
Last Updated: February 25, 2016
·
1.033K
· coreygrunewald
F5b375690fefcb29c25f2cfbb3286f19

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.

Say Thanks
Respond

3 Responses
Add your response

5242
D42a7264714dee5006b9c99d2567a320

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

over 1 year ago ·
5243
F5b375690fefcb29c25f2cfbb3286f19

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

over 1 year ago ·
5245
D42a7264714dee5006b9c99d2567a320

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

over 1 year ago ·