In JavaScript, functions can be attached to objects, making them act very much like methods in object-oriented languages. Here’s how you can do this and use the this
keyword to interact with other object properties.
Since functions in JavaScript are first-class citizens, meaning they can be treated like any other value, they can be assigned as properties of objects. This allows you to call them via the object, similar to methods in classes from other languages.
In this example, deposit
and withdraw
are functions that manipulate the balance
property of the account
object. The this
keyword refers to the current instance of the object, allowing access to its properties.
With recent enhancements to JavaScript, you can define methods more succinctly, using a syntax that’s cleaner and more akin to traditional object-oriented programming.
This newer method syntax provides a more concise way to define functions that are meant to behave like methods, enhancing the readability and maintainability of your code. Whether you use the traditional function syntax or this newer method syntax depends on your preference for clarity or brevity in your codebase.