码迷,mamicode.com
首页 > Web开发 > 详细

js bind方法的实现

时间:2018-12-04 22:42:00      阅读:361      评论:0      收藏:0      [点我收藏+]

标签:fun   返回   上下文   上下   arguments   javascrip   context   bsp   执行   

Function.prototype.bind = function(){
  var self = this, // 保存原函数
  context = [].shift.call( arguments ), // 需要绑定的 this 上下文
  args = [].slice.call( arguments ); // 剩余的参数转成数组
  return function(){ // 返回一个新的函数
    return self.apply( context, [].concat.call( args, [].slice.call( arguments ) ) );
    // 执行新的函数的时候,会把之前传入的 context 当作新函数体内的 this
    // 并且组合两次分别传入的参数,作为新函数的参数
  }
};
var obj = {
  name: ‘sven‘
};
var func = function( a, b, c, d ){
  alert ( this.name ); // 输出:sven
  alert ( [ a, b, c, d ] ) // 输出:[ 1, 2, 3, 4 ]
}.bind( obj, 1, 2 );
func( 3, 4 );

  

 

js bind方法的实现

标签:fun   返回   上下文   上下   arguments   javascrip   context   bsp   执行   

原文地址:https://www.cnblogs.com/huang-gua/p/10066929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!