Analog call apply

1. call

function call for designating call context object when this, such

var a = 9;
const obj = {
  a: 2,
  show: function() {
    console.info(this.a);
  }
};

obj.show(); //2

const other = {
  a: 99
};

obj.show.call(other); //99

Use objects directly call its function when, this points to the function of the object,

Function.prototype.call2 = function(context, ...args) {
  context.prop = this; //将 call2的调用者 object.show 赋值给给上下文对象
  context.prop(...args); // 通过上下文对象调用被call的函数
  delete context.prop; // 不能改变context对象,所以调用完 要删除额外属性
};

obj.show(78); //2
obj.show.call2(other, 34); //99

But such an approach is extended operator ES6, so you can improve, prop attribute may conflict with an existing property context, you can use the symbol to improve

2. apply

Apply the second parameter is an array, or an array of class

var a = 9;
const obj = {
  a: 2,
  show: function(age, name, sex) {
    console.info(this.a, age, name, sex);
  }
};

obj.show(34, 'geek', 'male'); //2

const other = {
  a: 99
};

obj.show.call(other, 25, 'bill', 'jin'); //99
obj.show.apply(other, [25, 'bill', 'jin']); //99

The above test results obtained are as follows

34 is 2 'Geek' 'MALE'
99 25 'Bill' 'Jin'
99 25 'Bill' 'Jin'
the need to apply a second parameter to the calling function expansion apply at the time of the analog apply

Function.prototype.apply2 = function(context, args) {
  context.prop = this;
  context.prop(...args);// 需要展开
  delete context.prop;
};


obj.show.apply2(other, [9, 8, 7]);

Guess you like

Origin blog.csdn.net/weixin_33912453/article/details/90846796
Recommended