JavaScript模拟bind方法

目前大部分高级浏览器都实现了内置的 Function.prototype.bind,用来指定函数内部的 this指向,对于还没有支持原生的 Function.prototype.bind 的就需要手动模拟实现,一个简易版bind方法,可以这样实现:

Function.prototype.bind = function (context) {
  var _this = this; // 保存原函数
  return function () { // 返回一个新函数
    return _this.apply(context, arguments); // 把之前传入的context当做新函数体内的this
  }
}
// 验证代码
var person = {
  name: 'Anne'
};
var person1 = function () {
  console.log(this.name); // 输出结果:Anne
}.bind(person);
person1();

如果我们想在函数使用时可以预先加入一些参数,那么bind方法可做如下改版来实现:

// 升级版bind, 支持传入参数
Function.prototype.bind = function () {
  var _this = this, // 保存原函数
  context = [].shift.call(arguments); // 绑定this上下文
  args = [].slice.call(arguments); // 剩余参数转成数组保存
  return function () {
    return _this.apply(context, [].concat.call(args, [].slice.call(arguments))); // 执行新函数把之前传入的context作为新函数的this,合并两次传入的参数作为新函数的参数
  }
}
// 验证代码
var obj = { 
  name: 'Marry1' 
 }; 
 var obj1 = function(){ 
  console.log ( this.name ); // 输出:Marry 
  console.log ( [...arguments] ) // 输出:[ 1, 2, 3, 4, 5 ] 
 }.bind( obj, 1, 2 ); 
 obj1( 3, 4, 5 );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

遇见小美好

每一笔打赏都见证了你的努力💪

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值