0

I have an object I'm trying to set a property to. However, I'm getting the type error Uncaught TypeError: Cannot set property 'meh' of undefined.

I'm trying to set this property using prototype.

greenify = {
    color: function(){
        console.log("Turned green");
    }
};

greenify.prototype.meh = function(){
    console.log("Off");
}

console.log(greenify);

Can anyone explain why it's claiming the greenify object is undefined and how to fix it?

  • Without talking about that code, can you try to explain what you want to do? – Mulan Jun 02 '16 at 12:09
  • 1
    [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – Andreas Jun 02 '16 at 12:12
  • @naomik how's it not clear what I'm trying to do? –  Jun 02 '16 at 12:14
  • 2
    @Robert: Just to be sure you understand, the error isn't claiming that `greenify` is undefined. It's telling you that the `.prototype` property of the `greenify` object is undefined. `greenify` itself is fine. There's just no automatic `.prototype` property created. That's just for functions. –  Jun 02 '16 at 12:21
  • It's amusing that it's marked as a duplicate when this question is asked why an error is occurring where as the others ask the purpose of something. Classing SE not knowing how to flag something and getting bent out of shape because they can't read code. –  Jun 02 '16 at 12:39

1 Answers1

0

Can anyone explain why it's claiming the greenify object is undefined and how to fix it?

greenify needs to be a function for it to have prototype property.

Try

function greenify() {
    this.color = function(){ //also used this.color so that color method can be used later
        console.log("Turned green");
    }
};

greenify.prototype.meh = function(){
    console.log("Off");
}

console.log(greenify);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Awesome, thank you. How would I go about doing this using an object literal instead of a constructor function? –  Jun 02 '16 at 12:12
  • @Robert Object needs to be a function for it to have a prototype chain. If you want to do it without function, then you need to remove `prototype` also, just directly assign a new property to `greenify` – gurvinder372 Jun 02 '16 at 12:14
  • Ah, ok. Thanks again –  Jun 02 '16 at 12:15