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

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

What is the use of bind() in JavaScript?

19条回答
  •  一整个雨季
    2020-11-21 06:57

    Simple example

    function lol(second, third) {
        console.log(this.first, second, third);
    }
    
    lol(); // undefined, undefined, undefined
    lol('1'); // undefined, "1", undefined
    lol('1', '2'); // undefined, "1", "2"
    
    lol.call({first: '1'}); // "1", undefined, undefined
    lol.call({first: '1'}, '2'); // "1", "2", undefined
    lol.call({first: '1'}, '2', '3'); // "1", "2", "3"
    
    lol.apply({first: '1'}); // "1", undefined, undefined
    lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"
    
    const newLol = lol.bind({first: '1'}); 
    newLol(); // "1", undefined, undefined
    newLol('2'); // "1", "2", undefined
    newLol('2', '3'); // "1", "2", "3"
    
    const newOmg = lol.bind({first: '1'}, '2');
    newOmg(); // "1", "2", undefined
    newOmg('3'); // "1", "2", "3"
    
    const newWtf = lol.bind({first: '1'}, '2', '3');
    newWtf(); // "1", "2", "3"
    

提交回复
热议问题