对bind&;调用JavaScript

对bind&;调用JavaScript,javascript,call,bind,slice,Javascript,Call,Bind,Slice,在阅读MDN中的Array.prototype.slice时,我发现了一个示例: 以下是示例代码: var unboundSlice = Array.prototype.slice; var boundSlice = Function.prototype.call.bind(unboundSlice); function list() { return boundSlice(arguments, 0); } var list1 = list(1, 2, 3); // [1, 2, 3]

在阅读MDN中的Array.prototype.slice时,我发现了一个示例:

以下是示例代码:

var unboundSlice = Array.prototype.slice;
var boundSlice = Function.prototype.call.bind(unboundSlice);

function list() {
  return boundSlice(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]
调用
列表(1、2、3)
时,函数调用过程是什么

  • 我知道在
    list()
    中,它调用
    boundSlice([1,2,3],0)
    。但是在
    boundSlice
    中发生了什么
  • 我知道
    boundSlice
    function.prototype
    call()
    函数的绑定函数,该
    值设置为
    Array.prototype的
    slice()
    函数
  • slice()?我猜最后一个调用是
    [1,2,3]。切片(0)
    ,对吗?如果我是对的,这怎么会发生,有人能向我解释一下内在的过程吗
  • 这基本上是:

    var boundSlice = function (thisArg, arg1) {
        unboundSlice.call(thisArg, arg1);
    };
    
    棘手的部分是它如何知道在
    未绑定切片上执行
    调用
    操作?这是因为
    call
    方法在内部使用
    this
    值来知道要调用哪个函数,并且因为我们使用
    …call.bind(unboundSlice)
    this
    值设置为
    unboundSlice
    ,所以它调用此方法

    例如,当我们执行
    Array.prototype.slice.call(arguments,0)
    时,
    call
    中的
    this
    值将是
    Array.prototype.slice
    ,因为
    this
    值在未更改时始终位于
    的左侧

    关于
    列表(1,2,3)
    的结果是
    [1,2,3]的假设是正确的。切片(0)

    请注意,
    list
    可以简单地实现为:

    function list() {
        return Array.prototype.slice.call(arguments);
        //or return [].slice.call(arguments);
    }
    

    基本上是说
    Array.prototype.slice.call([1,2,3],0)要理解这一点,您应该更多地研究“调用”和“绑定”
    
    function list() {
        return Array.prototype.slice.call(arguments);
        //or return [].slice.call(arguments);
    }