- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Object Methods
- Object methods are simply functions that are stored as properties within an object.
- Think of properties as the "nouns" (data) and methods as the "verbs" (actions) that the object can perform.
- They are executed by "calling" them on the object, and they have the unique ability to interact with the object's own data using the this keyword.
Developer Tip: Think of methods as a way to give your data behavior. Instead of having a function floating around your code that takes a user object as an argument, you can make that function a part of the user object itself.
Syntax:
const objectName = {
property1: value1,
property2: value2,
// Defining a method using a function expression
methodName: function(parameter1, parameter2) {
// Logic that uses the object's data
console.log(this.property1);
}
};
- methodName: The key used to access and call the function.
- parameter1, parameter2, ...: Standard function parameters used to pass external data into the method.
Why it is Used:
- Encapsulation: By grouping data (properties) and logic (methods) together, you make your code easier to debug and maintain. The object becomes a self-contained unit.
- Code Reusability: Methods allow you to define logic once and trigger it across various parts of your application whenever that specific object is present.
- Namespace Protection: Instead of having dozens of global functions that might conflict with each other, methods are scoped to the object they belong to.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
greet: function() {
console.log('Hello! Nice to meet you.');
},
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
person.greet(); // Output: Hello! Nice to meet you.
console.log(person.fullName()); // Output: John Doe
Best Practice: Use descriptive names for your methods. A method that calculates a total should be named
calculateTotal() rather than just done() or run().
Accessing Object Properties: Inside an object method, the this keyword refers to the "owner" of the function—which is the object itself. This allows the method to access other properties defined in the same object.
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
printDetails: function() {
// 'this' points to the 'person' object
console.log(`Name: ${this.firstName} ${this.lastName}, Age: ${this.age}`);
}
};
person.printDetails(); // Output: Name: John Doe, Age: 30
Common Mistake: Forgetting to use
this when accessing properties inside a method. If you just write console.log(firstName), JavaScript will look for a global variable named firstName instead of the property inside your object.
Arrow Function as Object Method: This is a major "gotcha" in JavaScript. Arrow functions do not have their own this binding. Instead, they inherit this from the surrounding (lexical) scope.
const calculator = {
value: 10,
add: (x) => {
// In this context, 'this' refers to the global window object (or undefined in strict mode)
// 'this.value' will be undefined!
return x + this.value;
}
};
console.log(calculator.add(5)); // Output: NaN (because 5 + undefined is NaN)
Watch Out: Avoid using arrow functions for methods if you need to access the object's properties via
this. Use the standard function syntax or the shorthand syntax instead.
Object Method Shorthand (ES6+): Modern JavaScript introduced a cleaner way to write methods that is now the industry standard. You can omit the function keyword and the colon entirely.
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
// Shorthand syntax
greet() {
console.log('Hello!');
},
fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
Real-World Example: A Shopping Cart
In a real application, you might use object methods to manage state. Here is how a simple cart object might look:
const cart = {
items: [],
addItem(product, price) {
this.items.push({ product, price });
console.log(`${product} added to cart.`);
},
getTotal() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
};
cart.addItem('Laptop', 1200);
cart.addItem('Mouse', 25);
console.log(`Total Price: $${cart.getTotal()}`); // Output: Total Price: $1225
Summary
- Function as Property: Object methods are simply functions assigned to an object's property keys.
- Encapsulation: They keep related data and logic grouped together, making code cleaner and more modular.
- The 'this' Binding: Methods use the
thiskeyword to reference the object they belong to, allowing them to read and update object properties. - Arrow Function Limitation: Arrow functions should generally be avoided for methods because they don't bind their own
thiscontext. - Modern Syntax: Use the ES6 shorthand (e.g.,
methodName() { ... }) for more concise and readable code.