我不明白如何将变量从init函数传递到我的对象中的bindEvent函数: 目前,我未定义。
var Fisheye = {
init: function () {
$('body').hide();
$(window).load(function() {
$('body').fadeIn('slow');
this.imgs = $('.pic').children('img');
this.originalWidth = $(imgs).first().css('width');
this.minWidth = 300;
imgs.width(300);
Fisheye.bindEvents();
});
},
bindEvents: function() {
$(this.imgs).toggle(this.toggleClick, this.toggleClick);
console.log(this.imgs); // Why do I get Undefined here?
},
toggleClick: function() {
//Todo
}
}
Fisheye.init();
如何在对象中将变量从函数正确传递给另一个?
谢谢!
答案 0 :(得分:1)
你可以这样做:
var Fisheye = {
init: function () {
var _this = this;
$('body').hide();
$(window).load(function() {
$('body').fadeIn('slow');
_this.imgs = $('.pic').children('img');
_this.originalWidth = $(_this.imgs).first().css('width');
_this.minWidth = 300;
_this.imgs.width(300);
_this.bindEvents();
});
},
bindEvents: function() {
$(this.imgs).toggle(this.toggleClick, this.toggleClick);
},
toggleClick: function() {
//Todo
}
}
Fisheye.init();
问题在于你处理程序中的“this”不是Fisheye的实例,而是窗口。
但是你的toggleClick会遇到类似的问题。对于那些人的解决方案可能是这样做:
bindEvents: function() {
var _this = this;
var toggleFunction = function(){_this.toggleClick()};
$(this.imgs).toggle(toggleFunction, toggleFunction);
},
答案 1 :(得分:0)
迅速只是结构,为函数添加参数
bindEvents: function(imgs) {
$(imgs).toggle(this.toggleClick, this.toggleClick);
console.log(imgs); // Why do I get Undefined here?
},...
关于init函数
...
var imgs = ..
Fisheye.bindEvents(imgs);