Skip to main content

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 own this (it points to the object itself when called as user.sayHi());
  • an arrow function => has no own this, so inside it this will 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)); // 6

Methods 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

MethodWhen to useExample
obj.method = function() {}Add a single methoduser.sayHi = ...
Object.assign(obj, { ... })Add several methodsObject.assign(user, { sayHi, sayBye })
prototype.method = ...Add a method to all instancesUser.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:

javascript
obj.newMethod = function() { ... };

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.