0

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..

2
  • "Making a second variable eye seems to solve the issue but I have no clue why.": Because with that you are creating a global variable. Commented Apr 6, 2013 at 16:38
  • No. this is an object which at that moment only exists inside the function and eye is a property of that object. this is a special variable in JavaScript, have a look at the MDN documentation: developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/…. Commented Apr 6, 2013 at 16:53

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to get this of Object Constructor without saving value of this in another local variable ???
@Givi no. The value of this is set upon each function invocation (including the invocation of your event handler). It's not an inherent property of any object. There are other ways of making sure that the right value of this is available, but they all amount to the same basic idea.
0
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" }

Live Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.