0

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')

Chumba
  • 1
  • 1
  • https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes: _"Note: The property of an object that points to its prototype is not called `prototype`. Its name is not standard, but in practice all browsers use `__proto__`. The standard way to access an object's prototype is the `Object.getPrototypeOf()` method."_ – CBroe Feb 03 '23 at 14:49
  • see also https://stackoverflow.com/questions/14450731/why-is-javascript-prototype-property-undefined-on-new-objects – danh Feb 03 '23 at 14:51
  • Does this answer your question? [Why is JavaScript prototype property undefined on new objects?](https://stackoverflow.com/questions/14450731/why-is-javascript-prototype-property-undefined-on-new-objects) – danh Feb 03 '23 at 14:52

1 Answers1

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335