Reputation: 3810
So I've searched far and wide across SO but wasn't able to find an answer to this (likely because I'm understanding it wrong).
I have a JS function defined like this (much simplified):
window.Gadget = function(name, cost){
this.name = name;
this.cost = cost;
this.hasBeenRevamped = false;
this.checkForUpdates = function(){
console.log("checking for updates...");
}
window.$(window).scroll(function() {
console.log("scrolling...");
this.checkForUpdates(); /* The this here is erroneously referring to jQuery and not my Gadget Object. I need to fix this but am not sure how*/
});
}
I am trying to find a way to call checkForUpdates() for all instances of Gadget, so if I have 10 Gadget objects they all check for updates when I call the function.
I ultimately want to call this function for all Gadgets whenever the window scrolls per the jQuery function $(window).scroll.
Whats the best way to achieve this? Currently, when the window scrolls, I'm seeing the console log for scrolling but then a messsage that there is no method checkForUpdates. I believe (this) is referring to the jQuery instance and not my Gadget instance. How can I have jQuery call my Gadgets instance of checkForUpdates?
Thanks in advance!
Upvotes: 0
Views: 596
Reputation: 6205
Try this:
window.Gadget = function(name, cost){
this.name = name;
this.cost = cost;
this.hasBeenRevamped = false;
this.checkForUpdates = function(){
console.log("checking for updates...");
}
var self = this;
window.$(window).scroll(function() {
console.log("scrolling...");
self.checkForUpdates(); /* self instead of this */
});
}
First of all, your definition of checkForUpdates
was wrong. You need to define it as a function for it to work.
Secondly, I added a variable named self
in your scope, so you can refer to the actual gadget object inside the jQuery scope.
You can read more in depth about scopes here.
Upvotes: 2
Reputation: 12325
It has to be a function. Like this...
this.checkForUpdates = function(){
// ... Your function logic
}
And regarding the this
in your jquery function, you can do this.
...
var thisObj = this;
window.$(window).scroll(function() {
console.log("scrolling...");
thisObj.checkForUpdates(); /* The this here is erroneously referring to jQuery and not my Gadget Object. I need to fix this but am not sure how*/
});
...
Upvotes: 2