我知道它是用来使参数成为一个真正的数组,但我不明白当使用Array.prototype.slice.call(参数);时会发生什么。
当前回答
// 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]
其他回答
假设你有:function。apply(thisArg, argArray)
apply方法调用一个函数,传入将绑定到this的对象 和一个可选的参数数组。
slice()方法选择数组的一部分,并返回新数组。
当你调用array。prototype。slice。Apply (arguments,[0])在参数上调用数组切片方法(bind)。
别忘了,这种行为的底层基础是完全集成在js引擎中的类型转换。
Slice只接受object(多亏了已有的参数。Length属性),并在对其执行所有操作后返回数组对象。
如果你试图用INT-value来处理String-method,你可以测试相同的逻辑:
String.prototype.bold.call(11); // returns "<b>11</b>"
这就解释了上面的表述。
/*
arguments: get all args data include Length .
slice : clone Array
call: Convert Object which include Length to Array
Array.prototype.slice.call(arguments):
1. Convert arguments to Array
2. Clone Array arguments
*/
//normal
function abc1(a,b,c){
console.log(a);
}
//argument
function: function abc2(){
console.log(Array.prototype.slice.call(arguments,0,1))
}
abc1('a','b','c');
//a
abc2('a','b','c');
//a
array. prototype.slice.call(参数)是将参数转换为数组的老式方法。
在ECMAScript 2015中,你可以使用Array.from或展开操作符:
let args = Array.from(arguments);
let args = [...arguments];
也许有点晚了,但所有这些混乱的答案是,在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