2017-05-10 16 views
0

私はちょうどモジュールJavascriptについて学び始めました。私はブイと呼ばれるオブジェクトを持っており、複数のタイプのブイがあります(これらは基本的にポップアップです)。親オブジェクトへのアクセス方法変数のスコープ?

ライブチャットの1つです。

私はすべてのコードを構造体のようなより多くのモジュールに変換していますが、何か問題を抱えていました。

コードは以下のとおりです。私は注意が必要な部分にコメントを残します。

変数$liveChatのcacheDom関数を調べます。

このliveChatを子要素として持つ理由(すべてのメソッドを親クラスに入れるのとは反対)は、親クラスのすべてに適用されない独自のメソッドを持つためです。私は複数のタイプのブイを持っています。 LiveChatはこれまでに作成した唯一のものです。私がliveChatに入れようとしているこれらの関数は、liveChatブイに固有のものになるでしょう。

/* Buoy */ 
(function{ 
    var buoy = { 
     init: function() { 
      this.liveChat.init(); 
      this.cacheDom(); 
      this.bindEvents(); 
     }, 
     cacheDom: function() { 
      this.liveChat.cacheDom(); 

      this.$document = $(document); 

      this.$buoyContainer = $("#buoy-container"); 
      this.$buoy = this.$buoyContainer.find(".buoy"); 
      this.$addDream = this.$buoyContainer.find(".buoy.addDream"); 
      this.$scheduleDream = this.$buoyContainer.find(".buoy.live-chat"); 
     }, 
     bindEvents: function() { 
      this.liveChat.bindEvents(); 
      /* Remove Focus */ 
      this.$document.on("click", this.removeFocusAll.bind(this.$buoy)); 
      /* Add Focus */ 
      this.$buoy.on("click", this.addFocus); 
      this.$liveChat.on("click",) 
     }, 
     addFocus: function() { 
      this.addClass("focus"); 
     }, 
     removeFocus: function() { 
      this.removeClass("focus"); 
     }, 
     /* Live chat */ 
     liveChat: { 
      init: function() { 

      }, 
      cacheDom: function() { 
       //This is where I need to access the parent variable "$document" which is initialized in the parents cacheDom method 
      }, 
      bindEvents: function() { 

      } 
     } 
    } 
    buoy.init(); 
}()); 
+0

として設定し、子供にthisに渡すことができます。しかし、あなたは 'buoy、$ document'を参照することができます。 – Bergi

答えて

0

その後、JavaScriptで「親オブジェクト」のようなものは何もありませんthis.parent

var buoy = { 
    init: function() { 
    this.liveChat.init(this); 
    this.cacheDom(); 
    this.bindEvents(); 
    }, 
    // ... 
    liveChat: { 
    init: function(parent) { 
     this.parent = parent; 
    }, 
    cacheDom: function() { 
     //This is where I need to access the parent variable "$document" which is initialized in the parents cacheDom method 
     this.parent.$document // do whatever you want here. 
    }, 
    // ... 
    } 
} 
関連する問題