美文网首页
3.手写call/apply/bind/slice

3.手写call/apply/bind/slice

作者: 静昕妈妈芦培培 | 来源:发表于2021-09-15 08:29 被阅读0次

1.手写call

Function.prototype.hyCall = function (thisArg, ...args) {
  //获取调用hyCall的函数对象
  var fn = this;
  //对绑定的thisArg做处理,确保thisArg最终一定是对象类型,除了null,undefined外
  thisArg =
    thisArg === null || thisArg === undefined ? window : Object(thisArg);
  thisArg.fn = fn;
  //执行当前调用hyCall的函数,接收函数返回值
  var result = thisArg.fn(...args);
  delete thisArg.fn;
  return result;
};

function sum(n1, n2) {
  console.log(this);
  return n1 + n2;
}

console.log(sum.hyCall("abc", 1,2));

2.手写apply

Function.prototype.hyApply = function (thisArg, args) {
  //获取调用hyCall的函数对象
  var fn = this;
  //对绑定的thisArg做处理,确保thisArg最终一定是对象类型,除了null,undefined外
  thisArg =
    thisArg === null || thisArg === undefined ? window : Object(thisArg);

  //执行当前调用hyCall的函数,接收函数返回值
  thisArg.fn = fn;
  args = args || [];
  var result = thisArg.fn(...args);
  delete thisArg.fn;
  return result;
};

function sum(n1, n2) {
  console.log(this);
  return n1 + n2;
}

console.log(sum.hyApply("abc", [2, 5]));

3.手写bind

Function.prototype.hyBind = function (thisArg, ...args) {
  //获取调用hyBind的函数
  var fn = this;
  //对thisArg进行处理
  thisArg =
    thisArg === null || thisArg === undefined ? window : Object(thisArg);

  return function proxyFn(...params) {
    //执行调用hyBind的函数
    thisArg.fn = fn;
    var totalArgs = [...args, ...params];
    var result = thisArg.fn(...totalArgs);
    delete thisArg.fn;
    return result;
  };
};

function foo() {
  console.log("foo函数被执行");
  return 20
}
function sum(a, b, c, d) {
  console.log(a, b, c, d);
}

var bar = foo.hyBind("abc");
console.log(bar());

var baz = sum.hyBind("bcd", 1, 2);
baz(3, 4);

var bbb = sum.hyBind("acd");
bbb(1, 2, 3, 4);
var ccc = sum.hyBind("acd", 1, 2, 3, 4);
ccc();

4.手写slice

Function.prototype.slice = function (start, end) {
  //获取调用slice的数组
  var arr = this;
  start = start || 0;
  end = end || arr.length;
  var newArray = [];
  //遍历数组
  for (var i = start; i < end; i++) {
    newArray.push(arr[i]);
  }
  return newArray;
};

var nums = [1, 2, 3, 4];
console.log(nums.slice(1, 3));

非常感谢王红元老师的深入JavaScript高级语法让我学习到很多 JavaScript 的知识

相关文章

网友评论

      本文标题:3.手写call/apply/bind/slice

      本文链接:https://www.haomeiwen.com/subject/buthgltx.html