2

I have a function foo which is called on window.scroll. I want to access the object variables inside foo, for example i want to print the value of hello from the parent object.

jsfiddle link

 var Object = {
 hello: "hello",

  foo: function(e){
      alert(this.hello); //Prints undefined! I want to get this.hello
  },

  scrollListener: function(){
    var _this = this;
    $(window).scroll(_this.foo);
  },
};
3
  • According to JSFiddle, that code is correct when called with Object.foo({}); Commented Aug 29, 2014 at 17:03
  • remove .hello from this and you'll see why. this in your context refers to window Commented Aug 29, 2014 at 17:04
  • i understand why this is not available. this refers to the scroll event Commented Aug 29, 2014 at 17:10

2 Answers 2

2

I think wrapping _this.foo in an anonymous function will do the trick.

Use this in window.scroll

$(window).scroll(function(){
      _this.foo();
});

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

There are 2 solution

1) use $.proxy to do the trick.

$(window).scroll( $.proxy(_this.foo,this) );

DEMO

2) Return the foo function and then call it.

foo: function(context) {
    var that = context;
    return function(e){ alert(that.hello); }
},

scrollListener: function(){
   var _this = this;
   $(window).scroll(_this.foo(_this));
},

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.