[英]Javascript scope issues when binding
我知道关于此问题的堆栈上有很多类似的问题,但是对于我一生来说,我无法理解代码中的问题。
尝试升级javascript,以便任何建议都会有所帮助。 我创建了一个对象来管理滑块功能。
var gMapSlider = {
mapSlideShow: false,
// why doesnt current place update when passed in
newMarker: null,
oldMarker: null,
mapSlideIn: function() {
this.contentSlide
$('#placeDetails').animate({right: '0'});
this.mapSlideShow = true;
},
mapSlideOut: function(func) {
if (typeof(func) != "function") func = function() {};
$('#placeDetails').animate({right: '-320px'}, null, null, func());
this.mapSlideShow = false;
},
mapSlideToggle: function() {
(this.mapSlideShow) ? this.mapSlideOut() : this.mapSlideIn();
},
contentSlide: function() {
if (this.newMarker) $('h1', '#placeDetails').text(this.newMarker.title);
},
mapSlide: function(marker) {
this.newMarker = marker;
if (this.oldMarker === this.newMarker) { //same marker showing
this.mapSlideToggle();
}
else if (this.oldMarker !== this.newMarker && !this.mapSlideShow) { //diff marker showing
this.contentSlide(marker);
this.mapSlideIn();
}
else if (this.oldMarker !== this.newMarker && this.mapSlideShow) {
var self = this;
console.log(self) //returns this object
this.mapSlideOut(function() {
console.log(self); // returns this object
self.contentSlide(this.newMarker);
self.mapSlideIn;
}).bind(self); // cannot read property 'bind' of undefined
}
this.oldMarker = this.newMarker;
}
}
几个问题
1)问题出在我的gMapSlider.mapSlide函数上。 如果我调用mapSlide函数,而最后一个else if语句适用,则会得到绑定错误的无法读取属性。 我有Google,但没有发现任何实际意义。 任何人都可以帮助我在这里做错什么。
2)这是在名称空间中管理功能的最佳方法吗? 我看到的大多数代码示例都在全局命名空间中使用函数,因此如果建议在Javascript中创建类似的对象,则需要澄清一下吗?
编辑@torazaburo谢谢,感觉像是一个合适的新手,这就是问题所在。 把它作为答案,我将把它解决。 对代码架构有什么建议吗?
this.mapSlideOut(function() {
console.log(self); // returns this object
self.contentSlide(this.newMarker);
this.mapSlideIn;
}).bind(self);
bind()
应该在函数对象上调用,但是您要在函数调用的结果上调用它
用这个:
this.mapSlideOut.bind(self,function() {
console.log(this); // returns this object
this.contentSlide(this.newMarker);
this.mapSlideIn;
});
上面的调用也会返回给您对该函数的引用,并将其绑定到self
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.