Methods
Since functions are values, we can assign them to object property names. This is the closest thing to "methods" in Object-Oriented languages that JavaScript offers. You can even use the this
keyword to access other object properties:
const account = { balance: 100, deposit: function(amount) { this.balance += amount; }, withdraw: function(amount) { this.balance -= amount; } } account.deposit(50); account.withdraw(20); console.log(account.balance);
The difference between the account
object and the createAccount
function (from the earlier section on closure) is that balance
is "publicly" accessible in the account
object. On the other hand, in createAccount
function, we used closure and lexical scoping to hide the balance
property.
Yet another function syntax
In newer versions of JavaScript, the following syntactic sugar can be used to declare "methods," which looks more like method syntax in Object-Oriented programming languages.
const account = { balance: 100, deposit(amount) { this.balance += amount; }, withdraw(amount) { this.balance -= amount; } } account.deposit(50); account.withdraw(20); console.log(account.balance);
this
and Arrow Functions
Arrow functions should not be used as methods because you cannot use the this
keywork to access object properties.
const account = { balance: 100, deposit: (amount) => { this.balance += amount; }, withdraw: (amount) => { this.balance -= amount; } } account.deposit(50); account.withdraw(20); console.log(account.balance);