Object Methods
In JavaScript, objects can have properties that are functions. These properties are called methods. Methods allow objects to encapsulate behavior and perform actions using their own data. This section will guide you through the basics of creating and using object methods, with practical examples and best practices.
In JavaScript, objects come with a variety of built-in methods that allow you to interact with and manipulate object properties in powerful ways. Below is a comprehensive list of the most commonly used built-in object methods, along with descriptions and quick code samples.
Built-In Methods
Object Creation and Assignment
// Merging objects using Object.assign()
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(returnedTarget); // { a: 1, b: 4, c: 5 }
console.log(target); // { a: 1, b: 4, c: 5 }
Property Definition and Inspection
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77; // Throws an error in strict mode
console.log(object1.property1); // 42
Prototype Management
const prototype1 = {};
const object1 = Object.create(prototype1);
console.log(Object.getPrototypeOf(object1) === prototype1); // true
Object Freezing and Sealing
const obj = {
prop: 42
};
Object.freeze(obj);
obj.prop = 33; // Throws an error in strict mode
console.log(obj.prop); // 42
Other Utility Methods
console.log(Object.is('foo', 'foo')); // true
console.log(Object.is(window, window)); // true
console.log(Object.is('foo', 'bar')); // false
console.log(Object.is([], [])); // false
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // false
console.log(Object.is(-0, -0)); // true
Notes:
Object Methods
provide a powerful way to interact with and manipulate objects in JavaScript, offering both utility and flexibility.- Understanding these methods is crucial for effective JavaScript development and can significantly improve code quality and performance.
FAQ - Built-in Methods
Q: What is the difference between Object.assign() and Object.create()?
A: Object.assign()
copies all enumerable own properties from one or more source objects to a target object, whereas Object.create()
creates a new object with the specified prototype object and properties.
Q: Can I modify a frozen object?
A: No, once an object is frozen using Object.freeze()
, you cannot add, remove, or modify any properties of that object.
Q: What is the use of Object.hasOwnProperty()?
A: Object.hasOwnProperty()
is used to check if an object has a specific property as its own property (not inherited through the prototype chain).
Q: How do Object.getPrototypeOf() and Object.setPrototypeOf() differ?
A: Object.getPrototypeOf()
returns the prototype of the specified object, while Object.setPrototypeOf()
sets the prototype of a specified object to another object or null.
Creating Methods
Method Syntax
You can define methods inside an object literal using the function keyword or the shorthand method syntax.
const person = {
name: "John",
age: 30,
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // "Hello, my name is John."
Shorthand Method Syntax
const person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // "Hello, my name is John."
Using this
in Methods
Context of this
The value of this
inside a method refers to the object that called the method.
const person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const anotherPerson = {
name: "Jane",
greet: person.greet
};
person.greet(); // "Hello, my name is John."
anotherPerson.greet(); // "Hello, my name is Jane."
this
inside a method refers to the object that called the method. This allows methods to access and manipulate the object's properties.
Adding Methods to Existing Objects
You can add methods to an existing object using dot notation or bracket notation.
const person = {
name: "John",
age: 30
};
person.greet = function() {
console.log(`Hello, my name is ${this.name}.`);
};
person.greet(); // "Hello, my name is John."
Practical Examples
Calculating Age
A method to calculate the age of a person based on their birth year.
const person = {
name: "John",
birthYear: 1990,
calculateAge() {
const currentYear = new Date().getFullYear();
return currentYear - this.birthYear;
}
};
console.log(`${person.name} is ${person.calculateAge()} years old.`);
Bank Account
A bank account object with methods to deposit and withdraw money.
const bankAccount = {
accountHolder: "John Doe",
balance: 1000,
deposit(amount) {
this.balance += amount;
console.log(`Deposited $${amount}. New balance: $${this.balance}.`);
},
withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
console.log(`Withdrew $${amount}. New balance: $${this.balance}.`);
} else {
console.log("Insufficient funds.");
}
}
};
bankAccount.deposit(500); // "Deposited $500. New balance: $1500."
bankAccount.withdraw(300); // "Withdrew $300. New balance: $1200."
bankAccount.withdraw(2000); // "Insufficient funds."
Todo List Manager
A todo list object with methods to add, remove, and display tasks.
const todoList = {
tasks: [],
addTask(task) {
this.tasks.push(task);
console.log(`Added task: "${task}"`);
},
removeTask(task) {
const index = this.tasks.indexOf(task);
if (index > -1) {
this.tasks.splice(index, 1);
console.log(`Removed task: "${task}"`);
} else {
console.log(`Task "${task}" not found.`);
}
},
displayTasks() {
console.log("Todo List:");
this.tasks.forEach((task, index) => {
console.log(`${index + 1}. ${task}`);
});
}
};
todoList.addTask("Learn JavaScript");
todoList.addTask("Build a project");
todoList.displayTasks();
todoList.removeTask("Learn JavaScript");
todoList.displayTasks();
Notes:
Object Methods
allow objects to encapsulate behavior and perform actions using their own data.this
inside a method refers to the object that called the method, providing access to the object's properties.Methods
can be added to existing objects using dot notation or bracket notation.
FAQ
Q: What is the benefit of using methods in objects?
A: Methods encapsulate behavior within objects, making the code more modular and easier to maintain. They allow objects to perform actions using their own data.
Q: Can I use arrow functions as methods in objects?
A: While you can use arrow functions as methods, it is generally not recommended because arrow functions do not have their own this
. They inherit this
from the parent scope, which can lead to unexpected behavior.
Q: How can I iterate over methods in an object?
A: You can use a for...in
loop to iterate over all properties, including methods. Alternatively, you can use Object.keys
or Object.entries
to work with arrays of property names and values, and filter out methods based on the type.
Q: Can methods be inherited in JavaScript?
A: Yes, methods can be inherited through prototypes. When an object is created using a constructor function or class, it inherits methods defined on the prototype of that constructor or class.