我对这些用例的差异感到困惑:
// CASE 1: Two separate attempts, neither work (see comments)
var circle = new google.maps.Circle({
// and then a bunch of properties, all work fine. Including this to show you
// where the variable I'm trying to use in call() came from
});
circle.initListeners = function(){
this.addListener('mouseover', function(){
// Works if circle is named explicitly in explodeView (see code below),
// doesn't work with .call(circle) here, this.setRadius() in explodeView
explodeView().call(circle);
// Both work fine
this.infoWindow.setPosition(this.getBounds().getNorthEast());
this.infoWindow.open(map);
// Works with circle.getCenter, not with .call(circle) and this
this.timer = setInterval(function(){
map.panTo(this.getCenter());
}, 1000).call(circle)
// Works with circle.setRadius, not with this.setRadius
function explodeView(){
var radiusExtender = ((300 - tweet.stats.reach) + 1) / 60;
radiusExtender > 1.15 ? this.setRadius(radiusExtender * radius) : this.setRadius(radius * 1.15);
}
});
});
将此与以下 .call()
的使用进行比较,这是我在收到 “this does not have method ._togCircVis(...)”
错误后实现的当调用没有 .call(map)
的函数时:
// CASE 2: Works
// Call to function I added to circle prototype
map._togCircVis.call(map)
// Successfully receives map and executes correctly
google.maps.Map.prototype._togCircVis = function(){
this.circles.forEach(function(circle){
circle.getMap() != null ? circle.setMap(null) : circle.setMap(map);
})
}
当我尝试案例 1 中的代码时,我得到了与在将 .call(map)
添加到案例之前相同的 "this does not have method "
错误2. 当我尝试 .apply() 而不是 .call() 时,同样的事情(万福玛丽调试尝试)。我明白为什么添加案例 2 使其起作用,因为它澄清了调用的函数,当我使用 this
时,我正在谈论 map
对象,而不是 window 对象code> 用于变量赋值。但是,为什么它不适用于上述情况呢? MDN 文章帮助我开始使用 .call(map),但没有为我阐明其他用途。谢谢!
最佳答案
explodeView().call(circle);
这里你正常调用explodeView(没有调用),然后尝试在它返回的值上调用call
(未定义
)。相反,您应该编写explodeView.call(circle)
。您在这里遇到了非常相似的问题:
setInterval(function(){
map.panTo(this.getCenter());
}, 1000).call(circle);
您正在尝试对不是函数的对象调用call
。之前它是未定义
,这次它是一个数字( setInterval 返回一个数字)。您可以使用 bind像这样实现你想要的:
setInterval(function(){
map.panTo(this.getCenter());
}.bind(circle), 1000);
关于Javascript .call() 用法。一种有效,一种无效。有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36321915/