提问人:Yousef 提问时间:6/6/2023 最后编辑:InSyncYousef 更新时间:6/6/2023 访问量:46
了解 JavaScript 中的 .bind(this)
Understanding .bind(this) in JavaScript
问:
constructor() {
this._getPosition();
}
_getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
this._loadMap.bind(this)
,() => {
alert("could not get your position")
})
}
}
我们怎么知道 bind 参数中的 this 指的是什么?
有关更多上下文,请参阅以下函数this._loadMap.bind(this)
_loadMap()
_loadMap(position) {
const {latitude} = position.coords
const {longitude} = position.coords
let coords = [latitude, longitude]
this.#map = L.map('map').setView(coords, 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.#map);
L.marker(coords)
.openPopup()
.addTo(map)
.bindPopup('You are here!')
this.#map.on("click", function(mapE) {
this.#mapEvent = mapE
form.classList.remove("hidden")
inputDistance.focus()
})
}
基本上,总结一下一切。构造函数执行 _getPosition 函数。我们使用的是地理位置 API,其中 getCurrentPosition 方法接受成功和错误回调。在成功回调中,我想调用 loadMap。loadMap 的内容并不重要,我只是把它放在那里,以防有人想看。现在,当我只这样做时,我得到未定义,我知道情况就是这样,因为我处于严格模式,而前面的 this 将引用未定义,因为我们在一个函数中。现在,当我们这样做时,它就会起作用!但是为什么? this._loadMap
_loadMap
this._loadMap.bind(this)
答:
1赞
Pointy
6/6/2023
#1
当您传递给另一个函数以将其用作回调时,与的关系将被断开。最终调用时,它将没有要使用的值,并且将失败。this._loadMap
this
_loadMap()
this
通过使用 ,可以从该方法创建一个新函数,该函数与调用 的 where 的值永久关联。.bind()
_loadMap
this
.bind()
在你调用的上下文中,的值正是你在该上下文中使用它的其他地方的值。构造函数调用 ,以便函数 () 正确绑定到正在构造的对象。反过来,在对 的调用中,这仍然是那个对象。this
.bind()
this._getPosition()
_getPosition()
this
.bind()
评论
.bind
this._loadMap.bind(this)
(...args) => this._loadMap(...args)