gpt4 book ai didi

javascript - 理解javascript借用方法

转载 作者:数据小太阳 更新时间:2023-10-29 05:32:30 26 4
gpt4 key购买 nike

关于如何将函数的参数转换为真正的数组有很多解释。

但是我发现在bind 的帮助下简化代码非常有趣。

MDN Array.prototype.slice - Array-like objects

MDN Function.prototype.bind - Creating shortcuts

例如:

function list() {
return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

简化调用:

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

function list() {
return slice(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

如果您使用 apply 而不是 call,它的工作方式相同:

var slice = Function.prototype.apply.bind(unboundSlice);

它甚至可以通过使用来自任何函数实例的 call 来缩短,因为它与原型(prototype)中的相同,并且与来自数组实例的 slice 的方法相同:

var slice = alert.call.bind([].slice);

你可以试试

var slice = alert.call.bind([].slice);

function list() {
console.log(slice(arguments));
}

list(1, 2, 3, 4);

所以我想到的第一个非常奇怪的事情是在 apply 上调用 bind,但是 bind 的第一个参数应该是一个对象(作为上下文)而不是函数(Array.prototype.slice)。

另一个是以相同的方式处理 callapply

我编写 javascript 已经很长时间了,并且每天都自信地使用这些方法,但我不能全神贯注于此。

也许我遗漏了一些非常基本的细节。

谁能给个解释?

最佳答案

the first argument of bind should be an object (as context)

是的。

and not a function (Array.prototype.slice).

为什么不呢?首先,所有函数都是对象,所以这里没有错。

从另一个 Angular 来看,如果您使用 slice.call(...)slice.apply(...) 那么 slice 对象 call/apply 方法调用的上下文(接收者)。

What is the difference between binding apply and call?

applyBoundToSlice(arguments)callBoundToSlice(arguments) 没有区别。区别在于 applyBoundToSlice(arguments, [0, n])callBoundToSlice(arguments, 0, n) 如果你想将开始和结束参数传递给 切片

关于javascript - 理解javascript借用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38246313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com