我知道它是用来使参数成为一个真正的数组,但我不明白当使用Array.prototype.slice.call(参数);时会发生什么。
当前回答
别忘了,这种行为的底层基础是完全集成在js引擎中的类型转换。
Slice只接受object(多亏了已有的参数。Length属性),并在对其执行所有操作后返回数组对象。
如果你试图用INT-value来处理String-method,你可以测试相同的逻辑:
String.prototype.bold.call(11); // returns "<b>11</b>"
这就解释了上面的表述。
其他回答
假设你有:function。apply(thisArg, argArray)
apply方法调用一个函数,传入将绑定到this的对象 和一个可选的参数数组。
slice()方法选择数组的一部分,并返回新数组。
当你调用array。prototype。slice。Apply (arguments,[0])在参数上调用数组切片方法(bind)。
通常,调用
var b = a.slice();
将数组a复制到b中。然而,我们不能
var a = arguments.slice();
因为参数没有slice作为方法(它不是一个真正的数组)。
Array.prototype.slice是数组的slice函数。.call运行这个slice函数,并将this值设置为参数。
Array.prototype.slice=function(start,end){
let res=[];
start=start||0;
end=end||this.length
for(let i=start;i<end;i++){
res.push(this[i])
}
return res;
}
当你这样做时:
Array.prototype.slice.call(arguments)
Arguments在slice中变成this的值,然后slice返回一个数组
也许有点晚了,但所有这些混乱的答案是,在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
当正常调用.slice()时,这是一个数组,然后它只是迭代该数组,并完成它的工作。
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]