techie11
techie11

Reputation: 1387

javascript bind method parameters

I saw examples of 2 types of bind calls. first kind is:

    const book = {
      title: 'Brave New World',
      author: 'Aldous Huxley',
    }

    function summary() {
      console.log(`${this.title} was written by ${this.author}.`)
    }

    const braveNewWorldSummary = summary.bind(book)

now "this" in summary is now bond to the "book" object

the second kind is:

  function utilizationUpdate(chart, data) {....}

  function utilizationInit(component, btnGroup, data){
        ....
        var myChart = new Chart(ctx, {....}
        $(btnGroup).on("change", function() {
                    ...
                    fetch('{% url 'api_utilization' fac.fac_id %}?measure=' + measure + '&{{ request.GET.urlencode() }}' )
                    .then(status)
                    .then(json)
                    .then(utilizationUpdate.bind(this, myChart));
                }
            });
        }

"chart" in utilizationUpdate() is now bond to myChart.

Why in first bind() example, "this" is not an argument to be passed? but it is specified in the second bind() example?

Upvotes: 1

Views: 46

Answers (1)

Unmitigated
Unmitigated

Reputation: 89294

The first argument passed to bind is the this value and the other arguments are the additional arguments to the function. In the first case, it only sets the this value, while in the second case, it sets both the this value and the first argument. However, it is likely that the this value wasn't truly needed, so null could have been passed too.

Upvotes: 1

Related Questions