学习之apply,call,bind实现

目录

apply

简单说:创建一个新方法,用eval执行,完了之后删除掉,最后返回执行的结果。

Function.prototype.applyCopy = function(context) {
  context.fn = this;// 谁调用 this就是谁
  var args = arguments[1];
  if(!args || args.length == 0) return context.fn();
  var result = eval('context.fn("'+args.toString()+'")');
  delete context.fn;
  return result;
};      

call

Function.prototype.callCopy = function(context) {
  var args = [].shift.applyCopy(arguments);
  return this.applyCopy(this, [args]);
}

bind

Function.prototype.bindCopy = function(context) {
  var fn = this;
  return function() {
    return fn.apply(context, arguments[1]);
  }
}

demo

var s = {
  desc: 's.desc',
  name: '你好',
}

var name = 'window';
var desc = 'window => this'

function sayHi() {
  return {
    name: this.name,
    desc: this.desc,
  }
}

console.log(sayHi());
console.log(sayHi.bindCopy(s)());
console.log(sayHi.call(s));
console.log(sayHi.apply(s));

总结:apply是基础,call,bind都是在apply的基础上实现的。

猜你喜欢

转载自www.cnblogs.com/meetqy/p/11848475.html