2013-10-18 103 views
0

我想在我的js應用程序腳本中設置一組全局變量,它允許我在頁面和網站的整個函數中訪問它們。出於某種原因,即使我知道對象在那裏,我仍然在我的控制檯中未定義。爲什麼我不能在我的js函數中訪問全局變量?

這是我的js代碼段是很長,所以我想我會告訴你最重要的一點那是錯誤的JS(我認爲)

(function ($) { 

    "use strict"; 

    var global = function() { 
     this.init(); 
    }; 

    global.prototype = { 

     // ------------------------------------ 
     // Global variables 

      mainContainer : 'div#container', 
      tmbContainer : '.rsThumbsContainer', 
      tmbContainerT : '.rsThumbsContainer', 
      slider : '.collection #gallery-t-group', 
      body : 'body', 
      close : '<div class="close-button" id="close"><p class="icon-close"></p></div>', 
      socials : '.socialbar-vertical', 
      loader : '<div class="loader"></div>', 
      gallery : '.collection #gallery-t-group', 


     // ------------------------------------ 
     // Initialise 

     init: function() { 

      var app = this; 

      this.testGlobals(); 
      this.loadSlide(); 
      this.fakingIt(); 
      this.unloadSlide(); 
      this.mobileNav(); 
      this.loadThumbs(); 
      this.royalSlider(); 
      this.thumbsSwitch(); 
      this.functionResize(); 
      this.theSocialActivated(); 
      this.theSliderActivated(); 
      this.theSliderDeactivated(); 
      this.slideEventChange(); 

      console.log('======> new.global.js'); 


     }, 

     // ------------------------------------ 
     // Functions 
     testGlobals: function() { 
      console.log(body); 
     } 

    } 

    $(document).ready(function() { 
     new global(); 
    }); 

})(jQuery); 

在我的控制檯我得到

Uncaught ReferenceError: body is not defined 

是有一件簡單的事情我在這裏失蹤。

+0

我想你失蹤原型點更換

testGlobals: function() { console.log(body); } 

。至少,所有這些屬性都應該在構造函數中。 – elclanrs

+0

你的代碼不會創建*任何*全局變量。 – Quentin

回答

0

嘗試

testGlobals: function() { 
      console.log(this.body); 
     } 

testGlobals: function() { 
      console.log(global.body); 
     } 
+0

this.body完美工作,我想我需要在函數中聲明一些'var s = this;'並且像這樣訪問它,例如's.myFunction();'或's.find(element );' –

相關問題