[英]A javascript function that receives and returns functions
我有一个JavaScript函数:
function oneOf() {
return arguments[Math.floor(Math.random()*arguments.length)];
}
它的目的是接受可变数量的参数并吐出一个随机的参数,这是可行的。 我无法接受一系列对象方法并执行一个方法。 我该怎么做?
Function.prototype.apply
允许您将数组“ splat”到参数列表中:
function sayAll() {
console.log(arguments);
}
sayAll(1, 2, 3, 4);
// [1, 2, 3, 4]
sayAll.apply(null, ["a", "b", "c"])
// ["a", "b", "c"]
可以使用括号来调用函数(请参见上文)。
结合这两种见解,我们得到以下信息:
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
方面,那么我们就需要第三洞察力。
Function.prototype.bind
允许创建具有固定功能this
方面:
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`
我们也可以通过在this
语境oneOf
到Function.prototype.apply
:
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`.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.