[英]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.