0

It looks like when I'm using func.call(12) on some non-strict function func, it will use this = new Number(12) instead of this = 12 (see the snippet below). I noticed because typeof this was equal to 'object' instead of 'number'.

Is this expected behaviour? Is there any way around it?

function a() {
  return this;
}

function b() {
  'use strict';
  return this;
}

const x = a.call(12);
console.log(typeof x);
console.log(x);
console.log(x + 3);

const y = b.call(12);
console.log(typeof y);
console.log(y);
console.log(y + 3);
Jessy
  • 311
  • 4
  • 12

1 Answers1

2

Is this expected behaviour?

Yes, it's expected behaviour. In sloppy mode, this is always an object - casting primitives to their respective wrapper objects. And worse, null and undefined get replaced with the global object.

Is there any way around it?

Just always use strict mode.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375