To achieve call and apply

Implementation of the call. call the method. function cal () {} var obj = {} cal.call (obj, "sam", "kavin") change point, passing parameters

Function.prototype.call(context){

  // If the object passed is null or empty when pointing window

  var context = context || window

  was args = []

  // function call first to get the call, can be obtained with this

  context.fn = this;

  // We then put this array of arguments into the parameters of the function to be performed inside.

  for(var i =1,len<arguments.length;i<len;i++){

    args.push("arguments("+i+")")

  }

  var ret = eval("context.fn("+args+")")

  delete context.fn

  · return right

}

Implemented method of apply function cal () {} var obj = {} cal.call (obj, [ "sam", "kavin"]) to change the point, passing parameters

Function.prototype.apply2 = function(context,arr){

  var context = context || window;

  was res = ''

  context.fn = this;

  if(!arr){

    res = context.fn()

  }else{

    was angry = []

    for(var i =0,len=arr.length;i<len;i++){

      arg.push("arr("+i+")")

    }

    res = eval(context.fn(+arg+))

  }

  delete context.fn

  return res 

}

Guess you like

Origin www.cnblogs.com/samChens/p/11587110.html