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();
});
}
}
});
在這種情況下,「這」是全局對象(窗口或在嚴格模式下爲null)。您應該使用構造函數(new ...)爲對象函數創建自己的作用域(http://jsbin.com/dubuxonu/1/edit requirejs沒有錯誤) –
雖然我不想實例化它。它是一個靜態對象。我應該聲明對象並返回對象嗎?或者是創建一個構造函數並將其實例化爲唯一方法? – Seth
在這種情況下 - 在變量中保存對象的鏈接並用於調用像這樣的方法http://jsbin.com/sofekexe/1/ –