我知道堆栈上有很多关于这个问题的类似问题,但我一生都无法理解我的代码中的问题是什么。
正在尝试提高 JavaScript 水平,因此任何建议都会有所帮助。我创建了一个对象来管理 slider 功能。
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 语句,我会收到无法读取绑定(bind)属性的错误。我用谷歌搜索过,但没有发现任何真正相关的东西。谁能帮我解决我在这里做错的事情。
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;
});
上述调用还将返回对函数的引用,并将 this 绑定(bind)到 self
关于绑定(bind)时的 Javascript 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176233/