理解 JavaScript 中的 .bind(this)

huangapple go评论72阅读模式
英文:

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: '© <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.

huangapple
  • 本文由 发表于 2023年6月6日 10:06:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定