JavaScript实现bind方法

Function.prototype.pBind = function () {
        var self = this; // 保存原函数
        var context = [].shift.call(arguments); // 保存需要绑定的this的上下文
        var args = Array.prototype.slice.call(arguments); // 剩余的参数转为真数组
        console.log('args-------------',args)
        /**
         * 因为bind 绑定了上下文,因此 self.apply 的第一个参数,是之前我们保存的 context。接下来,我们将
         * bind 的其余参数和调用bind后返回的函数在执行的过程中接收的参数进行拼接,作为一个数组传入apply的
         * 第二个参数中去。这就完美的实现了 bind 函数的功能
         */
        return function () {
            console.log('arguments----------', [].slice.call(arguments))
            self.apply(context, [].concat.call(args, [].slice.call(arguments)))
        }
    }

	let name = '宋唐', age = 23;
    let obj = {
        name: '汉秦',
        objAge: this.age,
        outFun: function (fromW, toGo) {
            console.log(`${this.name}: 年龄 ${this.age} 来自${fromW} 去往 ${toGo}`);
        }
    };
    let testObj = {
        name: '子瑜',
        age: 27
    };
    obj.outFun.pBind(testObj, '河北', '北京')(); // 子瑜: 年龄 27 来自河北 去往 北京
    // obj.outFun.bind(testObj, '河北', '北京')(); // 子瑜: 年龄 27 来自河北 去往 北京
    obj.outFun.pBind(testObj, ['河北', '北京'])(2,3); // 子瑜: 年龄 27 来自河北,北京 去往 2
    // obj.outFun.bind(testObj, ['河北', '北京'])(2, 3); // 子瑜: 年龄 27 来自河北,北京 去往 undefined
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现一个 `bind` 方法,可以考虑使用原型链的方式来实现。 首先,我们需要定义 `bind` 方法,它接受一个 `this` 参数和任意数量的参数,并返回一个新的函数。这个新的函数会在调用时将 `this` 绑定到指定的对象,并传递给定的参数。 下面是一个使用原型链实现 `bind` 方法的示例代码: ```javascript Function.prototype.bind = function (context, ...args) { const fn = this; // 原函数 return function (...innerArgs) { return fn.apply(context, args.concat(innerArgs)); }; }; ``` 上述代码中,我们将 `bind` 方法定义在 `Function.prototype` 上,这样所有的函数对象都可以直接调用 `bind` 方法。 在 `bind` 方法内部,我们将原函数保存在 `fn` 变量中。然后返回一个新的函数,在这个新函数中,我们使用 `apply` 方法将原函数以指定的 `context` 为上下文来调用,并将传入的参数与新函数调用时的参数合并起来。 使用示例: ```javascript const obj = { name: 'Alice', }; function sayHello() { console.log(`Hello, ${this.name}!`); } const boundFn = sayHello.bind(obj); boundFn(); // 输出:Hello, Alice! ``` 在上述示例中,我们定义了一个对象 `obj` 和一个函数 `sayHello`。然后通过 `bind` 方法将 `sayHello` 函数绑定到 `obj` 对象上,并返回一个新的函数 `boundFn`。当调用 `boundFn` 时,它会在 `obj` 对象上下文中执行 `sayHello` 函数,并输出 `Hello, Alice!`。 希望这个示例可以帮助你理解如何使用原型链实现 `bind` 方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值