What is the use of the JavaScript 'bind' method?

后端 未结 19 2380
自闭症患者
自闭症患者 2020-11-21 06:24

What is the use of bind() in JavaScript?

19条回答
  •  没有蜡笔的小新
    2020-11-21 06:48

    Simple Explanation:

    bind() create a new function, a new reference at a function it returns to you.

    In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.

    You can preconfigure as many parameters as you want.

    Simple Example to understand bind:

    function calculate(operation) {
      if (operation === 'ADD') {
       alert('The Operation is Addition');
      } else if (operation === 'SUBTRACT') {
       alert('The Operation is Subtraction');
      }
    }
    
    addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
    subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
    
    

提交回复
热议问题