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
// 并且组合两次分别传入的参数,作为新函数的参数
}
};
context = [].shift.call( arguments ); 这代码有点不理解
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这行代码的作用是拿到第一个参数,赋值给context。
shift方法是删除数组第一个元素并返回该元素
因为 arguments 是一个类数组对象,没有真正数组所拥有的方法
故需要借用(call) 数组的方法(shift) 来使用
call() 的第一个参数是一个 this 值,表示是谁(arguments)借用的