Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does returning this result in an object? [duplicate]

Tags:

javascript

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?

like image 641
Ilia Choly Avatar asked Jan 23 '26 16:01

Ilia Choly


1 Answers

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.

like image 106
Pointy Avatar answered Jan 25 '26 08:01

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!