2014-03-29 57 views
0

我有一個requirejs模塊,我正在定義沒有依賴關係,我正在從我使用的對象文字移植。我認爲隨着回報的發揮,字面意思會大打折扣,但它會失去對this的引用。我一直收到錯誤Cannot call method 'getHeight' of undefined,我認爲我的對象內將出現this的每個實例。Javascript - 瞭解Requirejs模塊文字和「this」

它爲什麼這樣做?由於回報的範圍?這是我的...

define(function() { 
    return { 
    // Photos 
    photos: { 
     // Get photos wrapper 
     $photos: function(){ 
     return $('#photos'); 
     }, 
     setHeight: function() { 
     var height = this.header.getHeight(); // Here is where I get my first error "Cannot call method 'getHeight' of undefined" 
     return this.$photos().height($(window).height() - height); 
     }, 
     setWidth: function() { 
     var width = 0; 
     $('#photos').find('img').each(function() { 
      width += parseInt($(this).width()); 
     }); 
     return this.$photos().width(width); 
     }, 
     init: function() { 
     this.setHeight(); 
     this.setWidth(); 
     } 
    }, 
    // Header 
    header: { 
     $header: function() { 
     return $('header') 
     }, 
     top: function() { 
     var self = this; 
     return parseInt(self.$header().css('margin-top')); 
     }, 
     bottom: function() { 
     var self = this; 
     return parseInt(self.$header().css('margin-bottom')); 
     }, 
     getHeight: function() { 
     return this.$header().height() + (this.top() + this.bottom()); 
     } 
    }, 
    // Padd the Body 
    padBody: function() { 
     var padding = this.header.getHeight(); 
     return $('.body').css('padding-top', padding); 
    }, 
    loadImages: function() { 
     var self = this; 

     $("img[data-src]").unveil(200, function() { 
     $(this).load(function() { 
      $(this).removeClass('loading').addClass('loaded'); 
      self.photos.init(); 
     }); 
     }); 
    }, 
    init: function() { 
     var self = this; 

     // Fire everything 
     this.padBody(); 
     this.loadImages(); 

     $(window).on('resize', function() { 
     self.padBody(); 
     self.photos.init(); 
     }); 
    } 
    } 
}); 
+1

在這種情況下,「這」是全局對象(窗口或在嚴格模式下爲null)。您應該使用構造函數(new ...)爲對象函數創建自己的作用域(http://jsbin.com/dubuxonu/1/edit requirejs沒有錯誤) –

+0

雖然我不想實例化它。它是一個靜態對象。我應該聲明對象並返回對象嗎?或者是創建一個構造函數並將其實例化爲唯一方法? – Seth

+1

在這種情況下 - 在變量中保存對象的鏈接並用於調用像這樣的方法http://jsbin.com/sofekexe/1/ –

回答

1

在這種情況下,'this'是全局對象(窗口或null在嚴格模式)。你應該使用構造函數(new ...)爲對象函數創建你自己的範圍(jsbin.com/dubuxonu/1/edit requirejs沒有錯誤)

如果你不想要構造函數 - 用它來打電話給你在正確的上下文中的方法是這樣

(function(){ 
     var moduleObject = { 
     meth1: function(){}, 
     meth2: function(){ moduleObject.meth1() } 
     } 
     return moduleObject; 
    }); 

在這裏,我沒有使用「這個」,說直接在哪個對象,我想調用方法