因此,我在SO中搜索的范围非常广泛,但无法找到答案(可能是因为我对它的理解错误)。如何为对象的所有实例调用对象函数
我有这样的(很简单)定义的JS函数:
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*/
});
}
我试图找到一种方法来调用checkForUpdates()的小工具的所有实例,因此,如果我有10点小工具的对象,他们我在调用函数时都会检查更新。
我最终希望在窗口滚动每个jQuery函数$(window).scroll时,为所有小配件调用此函数。
什么是最好的方式来实现这一目标?目前,当窗口滚动时,我看到控制台日志进行滚动,但接下来的消息是没有方法checkForUpdates。 我相信(这)是指jQuery实例,而不是我的小工具实例。我如何让jQuery调用checkForUpdates的小工具实例?
在此先感谢!
var self =这个技巧! – jamis0n
感谢您的帮助!我很好奇我会用window.gadget.prototype来设置。这会是一种情况,我可以为所有新的Gadget实例设置一个变量为特定值?它看起来像这样:window.Gadget.prototype.hasBeenRevamped = false; – jamis0n
我不认为你想在这种情况下使用'prototype'。你必须像'var gadget = new window.Gadget()'那样创建Gadget的实例,然后你可以像这样设置实例的属性:'gadget.hasBeenRevamped = false;'。这是否回答你的尴尬? – JAM