Search code examples
javascriptprototype

Javascript prototype method "Cannot set property"


I'm always getting Cannot set property 'saySomething' of undefined but why? Am I making a mistake somewhere?

var Person = new Object();

Person.prototype.saySomething = function ()
{ 
  console.log("hello"); 
};

Person.saySomething();

Solution

  • Debugging tip: You get this ..of undefined errors when you try to access some property of undefined.

    When you do new Object(), it creates a new empty object which doesn't have a prototype property.

    I am not sure what exactly are we trying to achieve here but you can access prototype of function and use it.

    var Person = function() {};
    
    Person.prototype.saySomething = function() {
      console.log("hello");
    };
    
    var aperson = new Person();
    aperson.saySomething();