Reputation: 20350
I have two functions that I use as classes: Person
and Eye
.
Person
creates an Eye
object in itself. Later on I try to access the eye object created, with an event handler for whenever the user clicks on the web page.
function Eye(){
this.color="Green";
}
function Person() {
this.name="John";
this.eye = new Eye();
//eye=this.eye; // uncomment and everything works!
document.addEventListener("click", function(){
console.log(name); // This works
console.log(eye); // This doesn't work
})
}
var person= new Person();
Why doesn't this work? Making a second variable eye
seems to solve the issue but I have no clue why..
Upvotes: 0
Views: 682
Reputation: 96845
document.addEventListener("click", function() {
console.log(name);
console.log(eye);
});
In this context, name
refers to the name
property of the window object, since you didn't specify the object off of which you wanted to access it. window.name
just so happens to return "result"
on my implementation. And ogging eye
won't work because eye
has not been defined as a variable.
To fix this, use a variable to store the reference to the current object outside the event function and use it inside.
var ref = this;
document.addEventListener("click", function() {
console.log(ref.name);
console.log(ref.eye);
});
Output:
John Eye { color: "Green" }
Upvotes: 0
Reputation: 413976
It doesn't work because "eye" is not a variable, it's a property of an object. You're doing nothing to tell JavaScript what object to look at.
You'll have to save the value of this
in another local variable:
function Person() {
this.name="John";
this.eye = new Eye();
var person = this;
Then you can use that in the event handler:
console.log(person.eye);
Upvotes: 1