我知道它是用来使参数成为一个真正的数组,但我不明白当使用Array.prototype.slice.call(参数);时会发生什么。


当前回答

它使用slice方法数组have并调用它,它的this是arguments对象。这意味着它会像调用arguments.slice()一样调用它,假设参数有这样一个方法。

创建一个不带任何参数的切片将简单地获取所有元素——因此它只是简单地将元素从参数复制到数组中。

其他回答

它使用slice方法数组have并调用它,它的this是arguments对象。这意味着它会像调用arguments.slice()一样调用它,假设参数有这样一个方法。

创建一个不带任何参数的切片将简单地获取所有元素——因此它只是简单地将元素从参数复制到数组中。

别忘了,这种行为的底层基础是完全集成在js引擎中的类型转换。

Slice只接受object(多亏了已有的参数。Length属性),并在对其执行所有操作后返回数组对象。

如果你试图用INT-value来处理String-method,你可以测试相同的逻辑:

String.prototype.bold.call(11);  // returns "<b>11</b>"

这就解释了上面的表述。

也许有点晚了,但所有这些混乱的答案是,在JS中使用call()进行继承。 如果我们将其与Python或PHP进行比较,例如,调用分别用作super().init()或parent::_construct()。

这是它的用法的一个例子,阐明了所有:

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

参考:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance

arguments对象实际上不是Array的实例,也没有任何Array方法。因此,arguments.slice(…)将不起作用,因为arguments对象没有slice方法。

数组确实有这个方法,因为arguments对象与数组非常相似,所以两者是兼容的。这意味着我们可以在arguments对象中使用数组方法。由于数组方法是在考虑数组的情况下构建的,因此它们将返回数组而不是其他参数对象。

为什么使用array。prototype呢?Array是我们用来创建新数组的对象(new Array()),这些新数组被传递方法和属性,比如slice。这些方法存储在[Class]中。原型对象。因此,为了提高效率,我们不通过(new Array()).slice.call()或[].slice.call()来访问slice方法,而是直接从原型中获取它。这样我们就不必初始化一个新数组。

But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.

// We can apply `slice` from  `Array.prototype`:
Array.prototype.slice.call([]); //-> []

// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true

// … we can just invoke it directly:
[].slice(); //-> []

// `arguments` has no `slice` method
'slice' in arguments; //-> false

// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]

// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]