When using constructor function invocation in JavaScript, I have read that the this variable/keyword within the function will be bound to the new object and will return a object that has all the bound “this” values.
For example:
function Person() {
this.name = "bob";
this.age = 33;
}
var person = new Person(); // person object with name property of "bob" and age property of 33
If I do something like this, the same result will occur:
function Person() {
var localVar = "test",
fake = "fake";
this.name = "bob";
this.age = 33;
}
var person = new Person(); // person object with name property of "bob" and age property of 33 regardless of the local variables declared inside
However, if I do something like this, the variables/properties declared on self will return in the object
function Person() {
var self = this;
self.phone = "123-123-1222";
self.career = "programmer";
this.name = "bob";
this.age = 33;
}
var person = new Person(); // person object with name property of "bob" and age property of 33, phone of "123-123-1222" and career of "programmer"
In the last example, how does the interpreter know to return all four properties, even though two of them are bound to a local variable of this and not the actual “this” keyword.
In your last example,
selfis just a reference tothis. They’re interchangeable because they point to the same object: