JS手写——call bind apply

手写call

js 复制代码
// 手写call,将调用myCall的函数传递给context
Function.prototype.myCall = function(context,...args) {
  context = context ?? globalThis;
  const a = Symbol();
  context[a] = this;
  const result = context[a](...args);
  delete context[a];
  return result;
}

const obj = {name : 'Tom'};
function greet(age,city) {
  console.log(`${this.name},${age},${city}`);
}
greet.myCall(obj,18,'USa');

手写apply

js 复制代码
// 逻辑和call一样,就是接受的是参数数组
Function.prototype.myApply = function(context,argArray) {
  context = context ?? globalThis;
  const a =Symbol();
  context[a] = this;
  let result;
  if(Array.isArray(argArray)) {
    result = context[a](...argArray);
  }else {
    result = context[a]();
  }
  delete context[a];
  return result;
}

const obj = {name : 'Tom'};
function greet(age,city) {
  console.log(`${this.name},${age},${city}`);
}
greet.myApply(obj,[18,'usa']);

手写bind

js 复制代码
// 手写bind
Function.prototype.myBind = function(context,...args) {
  context = context ?? globalThis;
  const fn = this;
  const bound = function(...rest) {
    if(this instanceof bound) {
      return new fn(...args,...rest);
    }else {
      return fn.call(context,...args,...rest);
    }
  }
  // 保证:new bound() instanceof fn === true
  bound.prototype = Object.create(fn.prototype);
  return bound;
}




const person = {
 name: 'itheima'
}
function func(numA, numB, numC, numD) {
 console.log(this)
 console.log(numA, numB, numC, numD)
 return numA + numB + numC + numD
}

const bindFunc = func.myBind(person, 1, 2)

new bindFunc(3,4);
console.log(new bindFunc(5,6) instanceof func);
相关推荐
余人于RenYu4 小时前
Claude + Figma MCP
前端·ui·ai·figma
杨艺韬6 小时前
vite内核解析-第2章 架构总览
前端·vite
我是伪码农7 小时前
外卖餐具智能推荐
linux·服务器·前端
2401_885885047 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
小李子呢02117 小时前
前端八股性能优化(2)---回流(重排)和重绘
前端·javascript
程序员buddha8 小时前
深入理解ES6 Promise
前端·ecmascript·es6
吴声子夜歌8 小时前
ES6——Module详解
前端·ecmascript·es6
剪刀石头布啊9 小时前
原生form发起表单干了啥
前端
剪刀石头布啊9 小时前
表单校验场景,如何实现页面滚动到报错位置
前端
gyx_这个杀手不太冷静9 小时前
大人工智能时代下前端界面全新开发模式的思考(二)
前端·架构·ai编程