In this article, we take a closer look at JavaScript object methods, examining three distinct syntax styles: the classic function declaration (traditional), the modern arrow function expression, and the ES6 shorthand notation. By exploring these methods side by side, you’ll not only grasp their syntax intricacies but also uncover the unique advantages each one offers.
A JavaScript method is a function that is a property of an object. Methods are used to perform actions on the data contained within the object and can manipulate object properties or perform specific tasks related to the object.
Methods can be added to an object in several ways, such as using function declarations, function expressions, or the ES6 method shorthand. Methods provide a way to associate functions with objects and enable object-oriented programming in JavaScript.
Example
const objectWithMethods = {
// Method using Function Declaration
methodDeclaration: function() {
console.log("Method using Function Declaration");
},
// Function Expression with Arrow Syntax
methodExpression: () => {
console.log("Method using Function Expression with Arrow Syntax");
},
// ES6 Method Shorthand
methodShorthand() {
console.log("Method using ES6 Method Shorthand");
}
};
// Calling the methods
objectWithMethods.methodDeclaration();
objectWithMethods.methodExpression();
objectWithMethods.methodShorthand();
In the objectWithMethods
object, the first method represents traditional function syntax, where this refers to objectWithMethods
; the second method is an arrow function, where this
inherits from the surrounding context (typically the global object); and the third method uses the ECMA method shorthand, where this
also refers to objectWithMethods
.
Once you have an object containing the method, you can call it using dot notation. To call a method use dot notation followed by the method name and parentheses containing any required arguments.
Syntax
object.method();
Example
objectWithMethods.methodDeclaration();