手写实现 bind 函数

javascript 复制代码
Function.prototype.myBind = function(context) {
    if (typeof this !== 'function') {
        return
    }
    const args = [...arguments].slice(1)
    const fn = this
    return function Fn() {
        // 判断函数作为构造函数的情况,这个时候需要传入当前的函数的this给apply调用,其余情况都传入指定的上下文对象
        const target = this instanceof Fn ? this : context
        return  fn.apply(target, args.concat([...arguments]))
       
    }
}

function setName(name) {
    this.name = name
}

const obj = {
    age: 1
}
const setName1 = setName.bind(obj)
setName1('test')
console.log('正确结果',  obj)
const setName2 = setName.myBind(obj)
setName1('miome')
console.log('正确结果',  obj)
相关推荐
李妍.1 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy1 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
AI_小站2 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
felixking2 小时前
C++20 协程
开发语言·c++·协程
Zane1994124 小时前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
码农颜5 小时前
6.3 主函数流程剖析
开发语言·php
TheBestRucy5 小时前
Python 九阳神功:从零筑基到线程飞升
服务器·开发语言·网络·人工智能·python
研☆香5 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
草莓橙子碗6 小时前
Claude 使用指南
开发语言·python
longxiaozhang66 小时前
C# Array类:数组其实没那么难
开发语言·c#