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

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

What is the use of bind() in JavaScript?

相关标签:
19条回答
  • 2020-11-21 06:58

    The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

    x = 9;
    var module = {
        x: 81,
        getX: function () {
            return this.x;
        }
    };
    
    module.getX(); // 81
    
    var getX = module.getX;
    getX(); // 9, because in this case, "this" refers to the global object
    
    // create a new function with 'this' bound to module
    var boundGetX = getX.bind(module);
    boundGetX(); // 81
    

    Please refer this link for more information

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    0 讨论(0)
提交回复
热议问题