Issue with Lesson 23


#1



Hey, I've been having an issue with lesson Lesson 23.

These are the errors and code.


TypeError: Cannot read property 'species' of undefined


function Person(name,age) {
  this.name = name;
  this.age = age;
  this.species = "Homo Sapiens";
};

var sally = Person("Sally Bowles", 39);
var holden = Person("Holden Caulfield", 16);
console.log("sally's species is " + sally.species + " and she is " + sally.age);
console.log("holden's species is " + holden.species + " and he is " + holden.age);


#2

Try changing your variables so that the word new is before 'Person'.

var sally = new Person("Sally Bowles", 39);
var holden = new Person("Holden Caulfield" 16);

You have to put down the 'new' keyword before creating a new object, so that the computer will know what you want to do.


#3

Let's first examine the error message:

TypeError: Cannot read property 'species' of undefined

Since there is no line number we need to locate the first reference to species in our code and go from there.

Okay, so according to the constructor sally should have a species property, yet it doesn't.

Let's examine the function, Person(). Does it have a return statement? Well, no. It does not. So that means a direct call to this function will have undefined as a return value, or rather, its return value will be undefined. If it's undefined, it cannot have any properties.

A function has a special variable associated with it... this. It is an object, like everything else in JavaScript, and we can assign properties to it as we see fit. There are two ways we can render this back into calling scope. return this (which may come with surprises), or let the constructor function pass it back using the new operator. This is the optimal approach, and far more predictible.