手写实现 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)
相关推荐
勇气要爆发31 分钟前
LangGraph 实战:10分钟打造带“人工审批”的智能体流水线 (Python + LangChain)
开发语言·python·langchain
yy.y--36 分钟前
Java数组逆序读写文件实战
java·开发语言
Polaris北1 小时前
第二十七天打卡
开发语言·c++·算法
亓才孓2 小时前
【Exception】CONDITIONS EVALUATION REPORT条件评估报告
java·开发语言·mybatis
学无止境_永不停歇2 小时前
十一、C++11列表初始化、右值引用和移动语义
开发语言·c++
阿里嘎多学长2 小时前
2026-02-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
mjhcsp3 小时前
C++ 背包DP解析
开发语言·c++
尘缘浮梦3 小时前
协程asyncio入门案例 2
开发语言·python
juleskk3 小时前
2.15 复试训练
开发语言·c++·算法
一个处女座的程序猿O(∩_∩)O3 小时前
Python面向对象的多态特性详解
开发语言·python