【问题标题】:How to call an Objects function for all instances of the object如何为对象的所有实例调用对象函数
【发布时间】:2013-07-01 14:30:18
【问题描述】:

所以我在 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 的消息。 我相信 (this) 指的是 jQuery 实例,而不是我的 Gadget 实例。如何让 jQuery 调用我的小工具实例 checkForUpdates?

提前致谢!

【问题讨论】:

    标签: javascript jquery object prototype


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • 感谢您的帮助!我很好奇我会使用 window.gadget.prototype 来设置什么。在这种情况下,我可以为所有新的小工具实例将变量设置为特定值吗?会不会是这样的:window.Gadget.prototype.hasBeenRevamped = false;
    • 我认为您不想在这种情况下使用prototype。您必须创建一个像var gadget = new window.Gadget() 这样的小工具实例,然后您可以像这样设置实例的属性:gadget.hasBeenRevamped = false;。这回答了你的问题吗?
    【解决方案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*/ 
       });
    ...
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2022-01-11
      • 2015-04-15
      • 2014-12-03
      • 2015-10-22
      • 1970-01-01
      • 2018-03-18
      • 2013-11-05
      • 2017-08-04
      相关资源
      最近更新 更多