Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
执行所有值的Javascript对象文字表示法_Javascript_Object_Literals - Fatal编程技术网

执行所有值的Javascript对象文字表示法

执行所有值的Javascript对象文字表示法,javascript,object,literals,Javascript,Object,Literals,我想根据情况执行一个函数,从5个函数中选择。然后取该函数的返回值,用它执行一个额外的函数(每种情况相同) 我相信我所有的功能都是同步的 var x = require('./file2.js') export default (metadata) => { return (req, next) => { var fn = new x (req, next, metadata) var metric = (req.body.metric)

我想根据情况执行一个函数,从5个函数中选择。然后取该函数的返回值,用它执行一个额外的函数(每种情况相同)

我相信我所有的功能都是同步的

var x = require('./file2.js')

export default (metadata) => {
    return (req, next) => {
      var fn = new x (req, next, metadata)
      var metric = (req.body.metric)
      var choices = {
                "1": fn.one(),
                "2": fn.one(),
                "3": fn.one(),
                "4": fn.one(),
                "5": fn.two(),
                "6": fn.three(),
                "7": fn.four(),
                "8": fn.five()
      };
var jql = choices[metric]// When I put console.log's in all the function (one through five) they all print out.
file2.js:

var x = function (req, next, metadata) {
this.req = req;
this.next = next;
this.start = metadata.body.start;
}

x.prototype.one = function (){
   var jql = ['test',
    'AND ' + this.start].join("\n")
   return jql
}
module.exports = x;

如果你想做我认为你想做的事情,那么你需要这样的东西:

/*
 Since you want to call a method on an instance of a class, first bind them to 
 the proper scope (might want to rethink the name fn). 
 Function#bind creates a new function that executes with the proper scope
*/
const one = fn.one.bind(fn)
const two = fn.two.bind(fn)
const three = fn.three.bind(fn)
const four = fn.four.bind(fn)
const five = fn.five.bind(fn)

// Create your object of choices with these functions
const choices = {
  "1": one,
  "2": one,
  "3": one,
  "4": one,
  "5": two,
  "6": three,
  "7": four,
  "8": five
}

// Then you can use it like this:
choices['1'](/* whatever arguments it needs */)

你确定x已经定义了吗?你需要正确的文件吗?尝试执行console.log(x)并查看发生了什么
fn.1
语法无效。属性标识符语法不能以数字开头。我试图简化函数,结果搞砸了。fn.1()实际上是jiraCall.getleavel()您是否在任何地方定义了另一个名为choices的变量?/能否显示第一个文件的其余部分?这是令人困惑的,因为你的代码看起来很好。如果你解决了这个问题,你可能只想删除你的问题。非常感谢。我认为你的答案在金钱上是正确的。由于在ES6中,let绑定了作用域,您是否建议let choices={“1”:()=>fn.one()};然后调用选项[“1”]();这真的没关系。
“1”:()=>fn.one()
也可以