What is the difference between
function person(first_name, last_name) {
this.first = first_name
this.last = last_name
}
and this:
function person(first_name, last_name) {
var first = first_name
var last = last_name
}
Why only the first one makes person.first & person.last accessible outside the function?
The
thiskeyword within a function is called the invocation context.1) If you define your function as a member of an object (a method):
then the invocation context,
this, is the object to which the method is being added,myObject. So after callingmyObject.someMethod();above,myObject.xis then 2. The memberxis undefined until you call the method, unless you defined it before.2) If you use your function as a constructor with the
newkeyword, thenthisrefers to the new object that is being created:You’ll then have property
myX.xset to 3.Note that I called my constructor
MyX(), notmyX(). You should call yoursPerson(), notperson(). It’s just a convention, but it is useful to indicate that a function is meant to be used as a constructor.3) Finally, if you use
thiswithin a function that you call as neither a method nor a constructor, thenthisrefers to the global object (documentor, equivalently,window). Note however that if you are using javascript instrictmode (which you should do),thisis undefined in such a situation, which means that you basically cannot usethisin a function that is not a method or a constructor.Your specific question refers to case 2), the constructor.
this.x = 3in the constructor just sets propertyxof the newly created object. After some objectmyXis created, you can then access and modifyxexternally as any other object property usingmyX.x.