Methods in JavaScript
JavaScript supports methods defined on object types, which are similar to structs in some languages. Here’s an example:
When you run this code, you’ll get:
In JavaScript, methods are typically defined as part of the class declaration. Unlike some languages, JavaScript doesn’t have a concept of value vs pointer receivers - all object references in JavaScript act like pointers.
JavaScript uses prototypal inheritance, which means methods are shared across all instances of a class. This is similar to how methods work in some other object-oriented languages, but with some key differences in how inheritance and method lookup work under the hood.
Next, we’ll look at JavaScript’s mechanism for defining interfaces, which involves using TypeScript or Flow for static typing, or implementing duck typing in vanilla JavaScript.