Implement a call or apply

Referrer: Call and analog apply the depth of JavaScript to achieve  # 11

call definitions:

  fn.call (thisarg, arg1, arg2, ...) call to a function, which has a specified value and this provided the parameters are

call core:

  1, the function to the object's properties

  2, execution & delete function

  3, designated thisto the function and passing parameters to perform a given function

  4, if the parameter is not passed, the default pointing to window

First, to achieve a relatively simple method call:

var foo = { 
    value: . 1 , 
    bar: function () { 
        the console.log ( the this .Value) 
    } 
} 
foo.bar () // . 1, although here the this point to determine foo foo added to a property, it is not our We hope to get results

We went to see the following:

Function.prototype.call2 = function(content = window) {
    content.fn = this;
    let args = [...arguments].slice(1);
    let result = content.fn(...args);
    delete content.fn;
    return result;
}
let foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.call2(foo, 'blue', '18') // blue 18 1 call the perfect realization of the method is not very much so

apply the definition

  fn.apply (thisarg, [argsarray])   calls a function, as well as an array (or array-like object) parameters provided

apply different methods to achieve with a similar call just an argument

= Function.prototype.apply2 function (context = window) { 
    context.fn = the this 
    the let Result; 
    // determines whether the second parameter 
    IF (arguments [. 1 ]) { 
        Result = context.fn (arguments ... [. 1 ]) 
    } the else { 
        Result = context.fn () 
    } 
    Delete context.fn
     return Result 
}

 

  

  

Guess you like

Origin www.cnblogs.com/wuconghui/p/10973647.html