Deadpool
Deadpool

Reputation: 8240

Printing by prototype not working in JS

I am trying to make a constructor function. Then I am trying to use its prototype and printing "Peter". But it is showing an error.

function main(){

   var func1 = function(){
	this.name = "Peter";
	this.age = 27; 
	this.class = "10";
   }

   func1.prototype.printName = function(){
	console.log(this.name);
   }

   return func1; 
}

var a = main();

a.printName();

Upvotes: 0

Views: 31

Answers (1)

Felix Kling
Felix Kling

Reputation: 817080

You are assigning the constructor function func1 to a, not an instance of func1. Only instances of func1 have a printName method. At some point you need to call new func1() or new a(). E.g. you could do return new func1(); instead of return func1;.

Have a look at the following, simplified example.

var func1 = function() {
  this.name = "Peter";
  this.age = 27;
  this.class = "10";
}

func1.prototype.printName = function() {
  console.log(this.name);
}

var a = new func1();

a.printName();

I recommend to read eloquentjavascript.net - The Secret Life of Objects.

Upvotes: 3

Related Questions