0

I'm trying to access a field of a constructor from a nested function.

Here is my code:

var Box = function() {
  this.div = $("div#mydiv");
  this.guide = {
     div: $("div#mydiv2"),
     scroll: function() {
        $(document).scrollTo(this.div); //Want to scroll to mydiv2
        alert(Box.div.attr("id")); //Want to alert mydiv id
                                   //How do I access the div field of the Box constructor?
     }
  }
}

if I call the scroll method like this:

var a = new Box();

$("#button").click(function() {
a.guide.scroll();
});

Box.div is returning as undefined.

If I try to alert the id of the div property inside the scroll method as this.div it will use the div property inside the guide object. I've tried referencing the div field outside the guide object by using Box.div but this does not work. Please help me figure this out.

2 Answers 2

2

Add this to the first row of the Box function:

var Box = function() {
    var self = this;

Then in the alert, use self instead of this as this is not referring to the top level function (box).

$(document).scrollTo(self.div); 
Sign up to request clarification or add additional context in comments.

3 Comments

@Topener--so does self always refer to the top level function?
@codeninja yes, because you defined self there, it does refer to that this
@Topener--Thank you. The answer seems obvious after you learn it haha!
2

It's because the "this" objects in your scroll function refers to the function itself. You need to cache a reference to the outermost "this" object and use it instead. See this fiddle for an example:

http://jsfiddle.net/tuando/kBc5K/

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.