call, apply, bind


これは作者に読んでもらうための大きな文章です:)

関数thisをバインドする方法:call、apply、bind


function.call( this target, argument)


このターゲットを
  • に変更し、関数
  • を実行します.

    function.apply( this target, [argument])


    このターゲットを
  • に変更し、関数
  • を実行します.
  • callとの違いは、その論点が並んでいることです.
  • function.bind( this target)

  • this targetをthisに変更して終了します.関数は実行されません.
  • 使用モード
    const mangojang = {name: 'mangojang'};
    
    const sayName = function(fruit){
    	console.log(`my name is ${this.name}. I like ${fruit}`);
    } 
    
    sayName("mango"); // my name is . I like mango
    const setThis = sayName.bind(mangojang);
    setThis("mango"); // my name is mangojang. I like mango
    sayName.call(mangojang,"mango"); // my name is mangojang. I like mango
    sayName.apply(mangojang,["mango"]); // my name is mangojang. I like mango
    

    参考文献


    https://wooooooak.github.io/javascript/2018/12/08/call,apply,bind/
    https://www.zerocho.com/category/JavaScript/post/57433645a48729787807c3fd