kevin
kevin

Reputation: 3508

Object's prototype methods only returning function definitions, not executing.

I was reviewing the prototypal way of creating and "instantiating" objects and I've run into a problem. When I put this code into the browser's console to test it out, if I enter:

nUser1.myAge()  // only the function definition is returned, doesn't actually execute.

I thought that perhaps I needed to have a return statement on the method, but that made no difference. Plus, in my previous (successful) practice attempts they didn't need a return statement to return the output of the respective methods.

I've looked through the code several times and compared it to my other examples and nothing is standing out. I feel like the problem is right under my nose, but I'm not seeing it.

function normUserCreator(name, age, employed) {
  this.name = name;
  this.age = age;
  this.employed = employed;
};

normUserCreator.prototype.myName = function() {
  console.log("My name is: " + this.name + ".")
};
normUserCreator.prototype.myAge = function() {
  console.log("My age is : " + this.myAge + ".")
};
normUserCreator.prototype.employed = function() {
  if (this.employed === true) {
    console.log("I am employed");
  } else if (this.employed === false) {
    console.log("I am not employed");
  }
};

var nUser1 = new normUserCreator('Kevin', 26, false);

Upvotes: 0

Views: 37

Answers (1)

brk
brk

Reputation: 50326

The mistake is in this line

console.log("My age is : " + this.myAge + ".")

It is basically calling itself.Replace it with this.age

Also you can replace if (this.employed === true) with if (this.employed) same for else if condition

function normUserCreator(name, age, employed) {
  this.name = name;
  this.age = age;
  this.employed = employed;
};

normUserCreator.prototype.myName = function() {
  console.log("My name is: " + this.name + ".")
};
normUserCreator.prototype.myAge = function() {
  console.log("My age is : " + this.age + ".")
};
normUserCreator.prototype.employed = function() {
  if (this.employed) {
    console.log("I am employed");
  } else if (!this.employed) {
    console.log("I am not employed");
  }
};

var nUser1 = new normUserCreator('Kevin', 26, false);
nUser1.myAge()

Upvotes: 3

Related Questions