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?
您错过了new
关键字:
var tank1 = new tank();
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:
Person
object. function Person(...)
", setting the this
to a reference to the object it just created. Person
object to the caller after the function returns. For more information on the execution context, see here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.