码迷,mamicode.com
首页 > 移动开发 > 详细

学习之apply,call,bind实现

时间:2019-11-13 14:38:38      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:ref   一个   call   rgs   window   his   let   ||   copy   

目录

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的基础上实现的。

学习之apply,call,bind实现

标签:ref   一个   call   rgs   window   his   let   ||   copy   

原文地址:https://www.cnblogs.com/meetqy/p/11848475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!