js学习-apply,call,bind的实现

目录

apply

简单说:构建一个和调用aplly函数一样的字符串,用eval执行,完了之后删除掉,最后返回执行的结果。

Function.prototype.applyCopy = function() {
  var obj = arguments[0];
  obj.fn = this;
  var args = arguments[1];

  if(!args || args.length == 0) return obj.fn();

  // obj.fn参数
  var argsStr = '';

  for(var i in args) {
    argsStr += '"' + arguments[1][i] + '",';
  }

  var result = eval('obj.fn('+argsStr.replace(/,$/, '')+')');
  
  delete obj.fn;
  return result;
};  

call

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

bind

Function.prototype.bindCopy = function() {
  var _this = this;
  var obj = arguments[0];
  return function() {
    return _this.applyCopy(obj, arguments);
  }
}

demo

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

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

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

console.log(sayHi(12,'sayHi'));
console.log(sayHi.applyCopy(s, [12, 'applyCopy']));
console.log(sayHi.callCopy(s, 12, 'callCopy'));
console.log(sayHi.bindCopy(s)(12, 'bindCopy'));

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

posted @ 2019-11-13 14:29  meetqy  阅读(174)  评论(0编辑  收藏  举报