手写实现 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)
相关推荐
Mr YiRan20 小时前
C++面向对象继承与操作符重载
开发语言·c++·算法
一只鹿鹿鹿1 天前
智慧水利一体化建设方案
大数据·运维·开发语言·数据库·物联网
没有医保李先生1 天前
字节对齐的总结
java·开发语言
Elastic 中国社区官方博客1 天前
使用 Elastic 进行网络监控:统一网络可观测性
大数据·开发语言·网络·人工智能·elasticsearch·搜索引擎·全文检索
Codefengfeng1 天前
Python Base环境中加包的方法
开发语言·python
清水白石0081 天前
《Python 编程全景解析:从核心精要到测试替身(Test Doubles)五大武器的实战淬炼》
开发语言·python
六件套是我1 天前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
S-码农1 天前
Linux ——条件变量
linux·开发语言
清水白石0081 天前
《Python 编程全景解析:从核心精要到 Hypothesis 属性基测试的边界探索》
开发语言·python