接收和返回函数的javascript函数
我有一个JavaScript函数:接收和返回函数的javascript函数,javascript,methods,Javascript,Methods,我有一个JavaScript函数: function oneOf() { return arguments[Math.floor(Math.random()*arguments.length)]; } 它的设计目的是接收可变数量的参数,然后输出一个随机参数,这是可行的。我无法获取对象方法列表并执行一个。我该怎么做?Insight#1 允许您将数组“splat”到参数列表中: function sayAll() { console.log(arguments); } sayAll(
function oneOf() {
return arguments[Math.floor(Math.random()*arguments.length)];
}
它的设计目的是接收可变数量的参数,然后输出一个随机参数,这是可行的。我无法获取对象方法列表并执行一个。我该怎么做?Insight#1
允许您将数组“splat”到参数列表中:
function sayAll() {
console.log(arguments);
}
sayAll(1, 2, 3, 4);
// [1, 2, 3, 4]
sayAll.apply(null, ["a", "b", "c"])
// ["a", "b", "c"]
洞察#2
可以使用括号调用函数(参见上文)
结合这两种见解,我们得出以下结论:
function oneOf() {
var f = arguments[Math.floor(Math.random()*arguments.length)];
return f(); // Via insight #2
}
// Via insight #1
oneOf.apply(null, [someFunction, anotherFunction]);
如果这些函数是对象上的“方法”,并且需要保留它们的this
上下文,那么我们需要第三个细节
洞察#3
允许使用固定的上下文创建函数:
function sayWhatThisIs() {
console.log("This is", this);
}
var coolObject = {
cool: true,
sayWhat: sayWhatThisIs
};
coolObject.sayWhat();
// This is {cool: true, ...}
oneOf.apply(null, [coolObject.sayWhat.bind(coolObject),
sayWhatThisIs.bind(coolObject)]);
// Two variations of binding `sayWhatThisIs` to `coolObject`
洞察#3a
我们还可以将其中一个的上下文传递给:
你能包含不工作的代码而不是正在工作的代码吗?完全相同,但是你需要另外调用它。请看这里:这对我不起作用,可能是因为我调用了()中的一个吗从具有相同对象的方法的参数的对象?不-其中一个
应该不重要-您使用的是bind
还是apply
(来自insights 3/3a)?
function oneOf() {
var f = arguments[Math.floor(Math.random()*arguments.length)];
return f.apply(this);
}
onOf.apply(coolObject, [coolObject.sayWhat, sayWhatThisIs]);
// Now applying insight #3a to set `onOf`'s `this` context to `coolObject`.