Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 345
Samy Avatar asked Jan 23 '17 00:01

Samy


1 Answers

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();
like image 134
Ajay Narain Mathur Avatar answered Sep 30 '22 13:09

Ajay Narain Mathur