JavaScriptでコール()、apply ()およびbind ()を説明しました.


前回の投稿では、関数のコンストラクタについて説明しました.関数オブジェクトがどのようにそれから作成されたか、関数オブジェクトのプロパティとメソッド.
この記事では、次の3つの機能方法の詳細について説明します.
  • call ()
  • apply ()
  • bind ()
  • これらは基本的に関数を呼び出すために使用されます( bindを除いて、bind ()は必要に応じて使用できる新しい関数を返します).彼らはすべてを取るthis コンテキスト内の関数を実行するコンテキストに依存します.詳細にそれぞれを見てみましょう.

    call ()
    MDN definition : call ()メソッドは、指定したthis 個別に提供される値と引数.

    Syntax: func.call([thisArg[, arg1, arg2, ...argN]])

    • thisArg: optional (this will be the value upon which the function would call)
    • arg1, arg2, ...argN: optional (arguments of the function)
    • the first argument represents a value on which the function would call (it refers to the current object/the calling object)
    • other arguments represent the value to the parameter of the function

    例を見てみましょう.
    // defining a global variable
    var lastName = 'global_name';
    
    const func = function(firstName) {
        return firstName + " " + this.lastName; /** the value of 'this' 
        is defined how we call the function */
    }
    
    // this object is passed as the first argument to the call method
    var person = {
        lastName: 'person_name'
    }
    
    // calling the function usually
    func('Sachin'); // Sachin global_name
    
    /** calling the function using the call method and setting the 
    'this' value to the 'person' object */
    func.call(person, 'Sachin'); // Sachin person_name
    
    // using call method without passing the first argument
    func.call(); // undefined global_name
    
    // passing the first argument as null or undefined
    func.call(null, 'Sachin'); // Sachin global_name
    func.call(undefined, 'Sachin'); // Sachin global_name
    
    /******************** in strict mode*****************/
    func.call(); /** Cannot read property 'lastName' of undefined*/
    func.call(null, 'Sachin'); /** Cannot read property 'lastName' of null*/
    func.call(undefined, 'Sachin'); /** Cannot read property 
    'lastName' of undefined*/
    
    この例から分かるように、コールメソッドを使用して任意のオブジェクトの関数を呼び出すことができます.
    • When usually calling the function then this value will set to the global object window. This window object is having a property lastName which we defined globally in our code will return from the function.

    • When calling the function using the call method and passing the first argument a person object then this value will set to that person object (not window object this time) and its lastName property will return.

    • Using the call method without passing any arguments, this value will set to the global object window and its property lastName will return.

    • When the first argument passed is null or undefined then still the this will set to the global window object in this case.

    Caution: For strict mode

    In 'strict mode', the value of this will be undefined. To know about strict mode refer to this documentation.



    apply ()

    Syntax: func.apply(thisArg, [ argsArray])

    • thisArg: (this will be the value upon which the function would call)
    • argsArray: optional (arguments of the function passed in an array)

    apply ()はcall ()とほぼ同様です.
    例:
    var name = 'Sachin';
    
    const func = function (age, hobby) {
      return (this.name + ' is ' + age + ' years old and his hobby is '
      + hobby);
    };
    
    var person = {
        name: 'John'
    }
    
    func(); /** Sachin is undefined years old and his 
    hobby is undefined*/
    func.apply(); /** Sachin is undefined years old and his 
    hobby is undefined*/
    
    console.log(func() === func.apply()); /** true*/
    
    func('15', 'writing'); /** Sachin is 15 years old and his 
    hobby is writing*/
    func.apply(undefined, ['15', 'writing']); /** Sachin is 15 years 
    old and his hobby is writing*/
    func.apply(null, ['15', 'writing']); /** Sachin is 15 years 
    old and his hobby is writing*/
    
    /********* changing 'this' to 'person' object*********/
    func.apply(person, ['20', 'music']); /** John is 20 years 
    old and his hobby is music*/
    
    /**************** strict mode ***************/
    /** Cannot read property 'name' of undefined*/
    func(); 
    func('15', 'writing'); 
    func.apply();
    func.apply(undefined, ['15', 'writing']);
    
    /** Cannot read property 'name' of null */
    func.apply(null, ['15', 'writing']); 
    
    

    bind ()

    Syntax: func.bind(thisArg[, arg1[, arg2[, ...argN]]])

  • bind ()メソッドは関数のコピーを作成して返しますfunc .
  • その新しい機能が呼ばれるとき、それはそれを持ちますthis 値はthisArg .
  • arg 1 , arg 2 , ...,argnは、その新しい返された関数の引数に代入する引数である.
  • 例を挙げてこれを理解しましょう.
    // defining a person object
    /** this object has a property 'age' and a method 
    'getNameAndAge' */
    const person = {
        age: 42,
        getNameAndAge: function(name) {
            return name + ' ' + this.age;
        }
    }
    
    // calling the method on the 'person' object directly
    person.getNameAndAge('Sachin'); // Sachin 42
    
    // assigning the reference of the method to variable nameAndAge
    const nameAndAge = person.getNameAndAge;
    
    // calling the function assigned to nameAndAge by referencing it 
    nameAndAge('Sachin'); /** Sachin undefined (the function gets
    invoked at the global scope)*/
    
    // use of bind method
    const boundNameAndAge = nameAndAge.bind(person, 'Sachin');
    boundNameAndAge() /** Sachin 42 (bind method creates
    a new function and bounds 'this' value to 'person' object)*/
    
    // bind without any arguments
    const boundNameAndAge = nameAndAge.bind();
    boundNameAndAge('Sachin') // Sachin undefined
    
    // setting 'this' to 'undefined'
    const boundNameAndAge = nameAndAge.bind(undefined, 'Sachin'); 
    boundNameAndAge() // Sachin undefined
    
    // setting 'this' to 'null'
    const boundNameAndAge = nameAndAge.bind(null, 'Sachin'); 
    boundNameAndAge() // Sachin undefined
    
  • 実行中nameAndAge('Sachin'); , 私たちはグローバルな範囲でその機能を実行しています、そしてthis ここではグローバルwindow オブジェクトと定義されていませんage グローバルスコープでは、なぜそれがundefined .
  • const boundNameAndAge = nameAndAge.bind(person, 'Sachin');
  • bind メソッドは、nameAndage関数とsetのコピーを作成して返しますthis to person オブジェクト.新しく作成した関数を変数に代入しますboundNameAndAge . 我々が実行するときboundNameAndAge() , それはthis 設定するperson and age 資産person オブジェクトが返ります.
  • 引数がない場合やthis 設定するnull or undefined , the this 新しく作成された関数の値はthis 実行スコープの.

  • 結論
  • call ()およびapply ()はすぐに関数を実行しますが、bind ()は新しい関数を返します.
  • 関数が実行するオブジェクト/値はthis コンテキストで定義された値.
  • Thanks for reading. If you found this article helpful please like and share it with others so that they will also get the benefit. Feedbacks are welcome: | |