JavaScript Call function principle

call the principle of analysis must look at the last example.

1.call use examples

function add(c, d) {
  return this.a + this.b + c + d;
}

const obj = { a: 1, b: 2 };

console.error(add.call(obj, 3, 4)); // 10

2. The implementation principle is similar to the code below

const obj = {
  a: 1,
  b: 2,
  add: function(c, d) {
    return this.a + this.b + c + d
  }
};
console.log(obj.add(3,4)); //10

Pseudocode steps

// 1. Set the function object's properties 
 obj.fn = the Add
 // 2. execute the function 
obj.fn ()
 // 3. Delete the function 
 delete obj.fn

 

3. To achieve

3.1 based ES3 achieve call

= Function.prototype.es3Call function (context) {
   var Content = || context window; 
  content.fn = the this ;
   var args = [];
   // arguments class is an array of objects, prior to the need to preserve the length of the traversal, a first filtered parameter passing 
  for ( var I = . 1 , len = the arguments.length; I <len; I ++ ) {
     // avoid such incoming object 
    args.push ( ' arguments [ ' + I + ' ] ' ); 
  } 
  var Result = the eval ( ' content.fn ( ' + + args ' )');
  delete content.fn;
  return result;
}
console.error(add.es3Call(obj, 3, 4)); // 10

 

3.2 Based ES6 achieve call, rest of parameters es6

Function.prototype.es6Call = function (context) {
    var context = context || window;
    context.fn = this;
    var args = [];
    for (var i = 1, len = arguments.length; i < len; i++) {
        args.push(arguments[i]);
    }
    const result = context.fn(...args);
    delete content.fn;
    return result;
}

 

4. Examples

To test whether they really understand the call

function fn1(){
   console.log(1);
}
function fn2(){
    console.log(2);
}

fn1.call(fn2);     //输出 1
 
fn1.call.call(fn2);  //输出 2

 

analysis

/ * * 
* Fn1.call (Fn2) 
* = Fn1 fn2.fn 
* fn2.fn () 
* Delete fn2.fn 
* 
* fn1.call.call (Fn2) 
* = fn1.call fn2.fn 
* fn2.fn ( ) -> fn2.call () -> recursive -> The last execution window.fn2 () 
* the Delete fn2.fn 
* /

 

 

Reference blog:

https://www.cnblogs.com/donghezi/p/9742778.html  (example analyzes too complex, difficult to understand)

https://blog.csdn.net/u010377383/article/details/80646415  (principle of speaking well)

 

Guess you like

Origin www.cnblogs.com/SmilingEye/p/11401099.html