英文:
Understanding .bind(this) in JavaScript
问题
In this._loadMap.bind(this)
, the bind(this)
part is used to explicitly set the value of this
within the _loadMap
function when it's called later. In JavaScript, the value of this
can change depending on how a function is called. By using bind(this)
, you are ensuring that within _loadMap
, this
will always refer to the same context as in the outer scope, which is the instance of the object or class where this code is running.
In your code, when you call this._loadMap.bind(this)
, you are essentially creating a new function that, when invoked, will always have this
pointing to the same object as the constructor's scope. This ensures that this
inside _loadMap
refers to the instance of the object where _getPosition
was called, and not to a different context, like undefined
.
This technique is often used in JavaScript to manage the value of this
within callback functions, especially when dealing with event handlers or asynchronous functions, to maintain a consistent context.
英文:
constructor() {
this._getPosition();
}
_getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
this._loadMap.bind(this)
,() => {
alert("could not get your position")
})
}
}
In this._loadMap.bind(this)
how do we know what the this in the bind parameter refers to?
For more context, here is the
_loadMap()
function
_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: '&copy; <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()
})
}
Basically, to sum everything up. The constructor executes the _getPosition function. We are using a geolocation API where the getCurrentPosition method accepts a success and an error callback. In the success callback, I want to call loadMap. The content of loadMap is not important, I just put it there in case anyone wants to see it. Now, when I do this._loadMap
only, I get undefined and I know that is the case because I am on strict mode and the this before the _loadMap
will refer to undefined because we are inside a function. Now, when we do this._loadMap.bind(this)
it works! But why?
答案1
得分: 1
当您将 this._loadMap
传递给另一个函数以将其用作回调时,与 this
的关联被中断。当最终调用 _loadMap()
时,它将没有可用的 this
值,并且会失败。
通过使用 .bind()
,您创建了一个新的函数,该函数来自 _loadMap
方法,该函数将永久与您调用 .bind()
的位置的 this
值关联在一起。
在您调用 .bind()
的上下文中,this
的值恰好与您在该上下文中使用它的任何其他地方的值相同。您的构造函数调用了 this._getPosition()
,因此该函数 (_getPosition()
) 正确地将 this
绑定到正在构造的对象上。反过来,在调用 .bind()
时,this
仍然是该对象。
英文:
When you pass this._loadMap
to another function to use it as a callback, the relationship to this
is broken. When _loadMap()
is eventually called, it will not have a this
value to use, and it will fail.
By using .bind()
, you create a new function from the _loadMap
method, one that is permanently associated with the value of this
where you called .bind()
.
The value of this
in the context where you call .bind()
is exactly the value of this wherever else you would use it in that context. Your constructor function calls this._getPosition()
, so that function (_getPosition()
) correctly has this
bound to the object being constructed. In turn, in the call to .bind()
, this is still that object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论