Jessy
Jessy

Reputation: 311

Different typeof 'this' when calling/applying a strict function vs. a non-strict function

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

Upvotes: 0

Views: 39

Answers (1)

Bergi
Bergi

Reputation: 664936

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.

Upvotes: 2

Related Questions