Reputation: 33
Are symbols acting like objects in JavaScript or a Symbol object is being created under the hood in the following example:
const symbol = Symbol();
Symbol.prototype.sayHello = function () {
console.log("sayHello");
};
symbol.sayHello(); //"sayHello"
I know that in JavaScript the function Symbol cannot be invoked with the keyword "new". But can it be done behind the scenes? I already know that when we use methods on primitive values like this:
console.log("333".startsWith("33")); //true
A String object is being created and the method String.prototype.startsWith is being invoked. After that, the object is being garbage-collected. But is it the same case when we work with symbols? Even though we cannot explicitly invoke the function Symbol as a constructor function?
Upvotes: 0
Views: 100
Reputation: 664444
Yes, symbols are primitive values, and invoking methods on them works just like for strings or numbers - a wrapper object gets implicitly created that inherits from Symbol.prototype
.
You cannot create such a wrapper object using new Symbol
, but you still can create it by calling
const symbol = Symbol();
const wrapper = Object(symbol);
Upvotes: 2