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 account
object and createAccount
function from the earlier section on closure is that balance
is "publicly" accessible in account
object. In createAccount
function, we used closure and lexical scoping to hide balance
.
Yet another function syntax
Starting with ECMAScript 2015, a 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 does not have their own bindings to this
and should not be used as methods.
const account = { balance: 100, deposit: (amount) => { this.balance += amount; }, withdraw: (amount) => { this.balance -= amount; } } account.deposit(50); account.withdraw(20); console.log(account.balance);