Object methods after creation
Short answer
Yes, you can! You can just assign the object a new property whose value is a function.
Example
javascript
const user = {
name: 'Tim'
};
// add a method after creation
user.sayHi = function() {
console.log(`Hello, ${this.name}!`);
};
user.sayHi(); // "Hello, Tim!"We added the sayHi method after the object was declared -
and now it's a full-fledged method of the object.
You can add arrow functions (but be careful)
javascript
user.sayBye = () => {
console.log(`Bye, ${user.name}!`);
};
user.sayBye(); // "Bye, Tim!"The difference:
function()has its ownthis(it points to the object itself when called asuser.sayHi());- an arrow function
=>has no ownthis, so inside itthiswill not refer to the object.
Regular functions, not arrow functions, are usually used for methods.
Example with several methods
javascript
const calculator = {};
calculator.add = function(a, b) {
return a + b;
};
calculator.multiply = function(a, b) {
return a * b;
};
console.log(calculator.add(2, 3)); // 5
console.log(calculator.multiply(2, 3)); // 6Methods can be added any number of times, at any point.
You can add them via Object.assign()
javascript
const user = { name: 'Tim' };
Object.assign(user, {
sayHi() {
console.log(`Hello, ${this.name}`);
},
sayBye() {
console.log(`Bye, ${this.name}`);
}
});
user.sayHi(); // "Hello, Tim"
user.sayBye(); // "Bye, Tim"Convenient when you need to add several methods at once.
You can add a method to the prototype (it spreads to all objects)
javascript
function User(name) {
this.name = name;
}
User.prototype.sayHi = function() {
console.log(`Hello, ${this.name}`);
};
const tim = new User('Tim');
const oleh = new User('Oleh');
tim.sayHi(); // "Hello, Tim"
oleh.sayHi(); // "Hello, Oleh"This approach adds the method to all instances created via new User().
SUMMARY
| Method | When to use | Example |
|---|---|---|
obj.method = function() {} | Add a single method | user.sayHi = ... |
Object.assign(obj, { ... }) | Add several methods | Object.assign(user, { sayHi, sayBye }) |
prototype.method = ... | Add a method to all instances | User.prototype.sayHi = ... |
In one phrase:
Yes, in JavaScript you can add methods to an object at any time - just assign it a function, and it becomes a method:
javascriptobj.newMethod = function() { ... };
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.