Chumba
Chumba

Reputation: 1

How to add new method to existing object?

I tried this but it doesn't work:

const robot = {
    name: 'Marble',
    model: '5F',
    age: 1,
    
};

robot.prototype.sayHello = function(){return `Hello I am ${this.model}`} 

I get error: Uncaught TypeError: Cannot set properties of undefined (setting 'sayHello')

Upvotes: 0

Views: 159

Answers (1)

Quentin
Quentin

Reputation: 943217

It's the same way you add any other value to an existing object.

You add it to the object.

robot.sayHello = function ...

The prototype property is used on constructor functions / classes to add to all instances of the class.

class Robot {
    constructor(name, model, age) {
        this.name = name;
        this.model = model;
        this.age = age;
    }
}

const robot = new Robot('Marble', '5F', 1);
const robot2 = new Robot('ZYX', '6F', 5);

Robot.prototype.sayHello = function(){return `Hello I am ${this.model}`} 

console.log(robot.sayHello());
console.log(robot2.sayHello());

… although modifying a class after you create it isn't a great idea. Now we have class syntax we can build classes in one go.

Upvotes: 1

Related Questions