In JavaScript, it is possible to name class methods using symbols. You can do so by adding the symbol within square brackets ([]
) as the name of the method, for example, like so:
// ES6+ const sym = Symbol('foobar'); class Foo { [sym]() { return 'foo'; } } const foo = new Foo(); console.log(foo[sym]()); // 'foo'
You can implement well-known (or built-in) symbols in the same way. For example, to implement [@@toPrimitive]()
method in a class, you would do the following:
// ES6+ class Foo { [Symbol.toPrimitive](hint) { if (hint === 'number') { return 1234; } return null; } } const foo = new Foo(); console.log(Number(foo)); // 1234
It works in the same way for generator methods. Consider, for example, the following that implements the well-known [@@iterator]()
method:
// ES6+ class Foo { *[Symbol.iterator]() { yield 1; yield 2; yield 3; } } const foo = new Foo(); for (const val of foo) { console.log(val); // 1 2 3 }
It also works with static
methods. For example, the following implements the well-known [@@hasInstance]()
method:
// ES6+ class Person { constructor(name, age) { this.name = name; this.age = age; } static [Symbol.hasInstance](instance) { return instance.name && instance.age; } } const name = 'John Doe'; const age = 29; const person1 = new Person(name, age); const person2 = { name, age }; console.log(person1 instanceof Person); // true console.log(person2 instanceof Person); // true
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.