Reputation: 11
I'm working through a text book and a lesson introduces the use of dot notation when defining a constructor. (It is understood that there is other syntax to use to name a property.) When experimenting with permutations of the lesson, an outcome causes some confusion.
One outcome is expected, undefined, from the following example:
function person(){
person.thing = 2;
}
console.log(person.thing);
// outcome: undefined
However, an alternative experiment with first creating an object from the constructor produces an unexpected outcome for the value of person.thing
:
function person(){
person.thing = 2;
}
var bob = new person();
console.log(bob.thing);
// outcome: undefined
console.log(person.thing);
// outcome: 2
Why is the value for the property person.thing
now 2 after a differently named object, bob
, was created from the constructor?
Upvotes: 0
Views: 273
Reputation: 1
instead of using person
function person(){
person.thing = 2;
}
var bob = new person();
console.log(bob.thing);
// outcome: undefined
console.log(person.thing);
// outcome: 2
change it to this
function person(){
this.thing = 2;
}
var bob = new person();
console.log(bob.thing);
// outcome: 2
console.log(person.thing);
// outcome: undefined
did you notice the OUTCOME?
Upvotes: 0
Reputation:
person
always refers to that function object. When you call the person
function, it actually runs so it places that property on the object.
This is no different the function putting a property on any other object, like this:
var myObj = {}
function person() {
myObj.thing = 2
}
console.log("person.thing:", person.thing) // undefined
console.log("myObj.thing:", myObj.thing) // undefined
var bob = new person()
console.log("bob.thing:", bob.thing) // undefined
console.log("person.thing:", person.thing) // undefined
console.log("myObj.thing:", myObj.thing) // 2
So the only difference is that we're now adding the thing
property to the myObj
object instead of the person
function object.
So person
never has any relationship to the object being created by the constructor function... it is the constructor function.
Within the constructor function, the way to access the object being created is by using the this
keyword. So if you did this.thing = 2
, then bob.thing
would be 2
.
Upvotes: 1