2013-07-03 70 views
0

因此,我在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的小工具实例?

在此先感谢!

回答

2

试试这个:

所有的
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 */ 
    }); 
} 

首先,你的checkForUpdates定义是错误的。你需要将它定义为一个函数才能工作。其次,我在您的范围中添加了一个名为self的变量,因此您可以参考jQuery范围内的实际小工具对象。

您可以更详细地了解示波器here

+0

var self =这个技巧! – jamis0n

+0

感谢您的帮助!我很好奇我会用window.gadget.prototype来设置。这会是一种情况,我可以为所有新的Gadget实例设置一个变量为特定值?它看起来像这样:window.Gadget.prototype.hasBeenRevamped = false; – jamis0n

+0

我不认为你想在这种情况下使用'prototype'。你必须像'var gadget = new window.Gadget()'那样创建Gadget的实例,然后你可以像这样设置实例的属性:'gadget.hasBeenRevamped = false;'。这是否回答你的尴尬? – JAM

2

它必须是一个函数。像这样...

this.checkForUpdates = function(){ 
    // ... Your function logic 
} 

而且关于你的jQuery函数的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*/ 
    }); 
... 
相关问题