簡體   English   中英

接收並返回函數的javascript函數

[英]A javascript function that receives and returns functions

我有一個JavaScript函數:

function oneOf() {
    return arguments[Math.floor(Math.random()*arguments.length)];
}

它的目的是接受可變數量的參數並吐出一個隨機的參數,這是可行的。 我無法接受一系列對象方法並執行一個方法。 我該怎么做?

洞察#1

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"]

洞察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.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`

見解#3a

我們也可以通過在this語境oneOfFunction.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM