-1

I'm having some trouble with some basic javascript:

function tank(){
    this.width = 50;
    this.length = 70;
}

function Person(job) {
    this.job = job;
    this.married = true;
}
var tank1 = tank();
console.log(tank1.length);  //returns: Uncaught TypeError: Cannot read property 'length' of undefined

var gabby = new Person("student");
console.log(gabby.married);  //returns: true

The first console.log does not work, but the second console.log works. I'm a javascript beginner and I'm at a loss as to why the length property is undefined. Any help?

2 Answers 2

10

You missed new keyword:

var tank1 = new tank();
Sign up to request clarification or add additional context in comments.

Comments

1

When you execute tank(), the execution context for the function is the window object. What you are doing is adding "width" and "length" fields to the window object, and you can see this if you execute window.length and window.width after the tank() call. You should see the values 70 and 50. Since the tank function does not return a value, the statement var tank1 = tank(); effectively sets tank1 to undefined, hence the error you are getting.

In the second statement, you are calling the Person constructor, so by the time function Person(job) {...} executes, this is a reference to the Person object that you are creating. The new statement does the following:

  1. Create the Person object.
  2. Calls the constructor "function Person(...)", setting the this to a reference to the object it just created.
  3. Returns the new Person object to the caller after the function returns.

For more information on the execution context, see here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.