手写实现 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 分钟前
【从零写一个CAD 03】三个 double 值得单独一个类吗:把视图变换抽成 View
开发语言·c++·qt·学习·系统架构
PHP实战开发录14 分钟前
PHP接口大整数为什么变了
开发语言·php
临床数据科学和人工智能兴趣组4 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike7 小时前
php笔记
开发语言·笔记·php
Circ.8 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~9 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou14113610 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅10 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http