3

Can someone explain this behaviour to me?

Object.prototype.getThis = function () {
  return this;
};

var s = "some text";

console.log(s.getThis()); // [String 'some text']
console.log(typeof s.getThis()) // object

Why does getThis return an object?

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160

1 Answers1

3

When you use a string primitive value as if it were an object, JavaScript implicitly creates a String instance from it. It's as if you wrote

console.log(new String(s).getThis().toString());

Primitive values are not objects. However, all the primitive types have built-in Object wrapper types, and those wrapper types are where the various methods (like .charAt(), .trim(), .slice(), etc) are located.

edit — @Bergi points out in a comment that in "strict" mode, the runtime still locates methods from the String and Object prototypes as if a String instance were being created, but the methods are invoked such that this is a reference to the original primitive value.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • That's not 100% accurate. The method (from the object) still gets called on a primitive, with `thisArg` being the primitive value – Bergi Mar 19 '16 at 22:12
  • @Bergi thats ES2015 stuff right? So, instead of faking the synthesis of a String instance and letting it go at that, it makes some sort of weird thing and invokes the String or Object prototype methods with `this` bound to the original primitive? – Pointy Mar 19 '16 at 22:15
  • Nah, it's always been like that. I mean, since strict mode was introduced. – Bergi Mar 19 '16 at 22:16
  • @Bergi right by "ES2015" I basically meant "new-fangled". Makes sense and is less weird than the "boxing" objects. – Pointy Mar 19 '16 at 22:18