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

Gadget のすべてのインスタンスに対して checkForUpdates() を呼び出す方法を見つけようとしています。そのため、10 個の Gadget オブジェクトがある場合、関数を呼び出すと、すべてのオブジェクトが更新をチェックします。

最終的には、ウィンドウが jQuery 関数 $(window).scroll ごとにスクロールするたびに、すべてのガジェットに対してこの関数を呼び出したいと考えています。

これを達成する最良の方法は何ですか?現在、ウィンドウがスクロールすると、スクロールのコンソール ログが表示されますが、メソッド checkForUpdates がないというメッセージが表示されます。(これは) 私のガジェット インスタンスではなく、jQuery インスタンスを参照していると思います。jQuery で、checkForUpdates の Gadget インスタンスを呼び出すにはどうすればよいですか?

前もって感謝します!

4

2 に答える 2

2

関数でなければなりません。このような...

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

そしてthis、あなたのjquery関数については、これを行うことができます.

...
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*/ 
   });
...
于 2013-07-03T18:46:07.583 に答える
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 スコープ内の実際のガジェット オブジェクトを参照できます。

スコープの詳細については、こちらをご覧ください。

于 2013-07-03T18:46:25.653 に答える