Given that Javascript is not the language I program in most of the time, I tend to make the mistake of referring to all functions as methods. There is in fact, a subtle difference.
In Javascript, a method is a function that is assigned to an object.
Here, speak() is a method on the chicken object:
const chicken = {
name: "Clive",
speak: () => {
console.log("BWARK!")
}
}
chicken.speak()
Written as a function, we would have:
const speak = () => {
console.log("BWARK!")
}
speak()
It's important to note that when we write a method as an arrow function, it doesn't have access to the other properties on the object. For instance:
const chicken = {
name: "Clive",
noise: "BWARK!",
speak: () => {
console.log(`${this.noise}`)
}
}
chicken.speak()
When run, this will return a noise most uncharacteristic of a chicken:
undefined
Written as a traditional function however, we have access to the object using this:
const chicken = {
name: "Clive",
noise: "BWARK!",
speak: function() {
console.log(`${this.noise}`)
}
}
chicken.speak()
BWARK!