JavaScript对象参数 - 似乎合法

时间:2012-08-23 02:32:35

标签: javascript function object

有许多JavaScript函数可以直接接受对象,这里有一些例子。这不是特定于jquery的$.ajax()或nodejs模块request()这两个函数,两者都只是示例。

$.ajax({
  method: "post",
  data: {'hello':'world'},
})

request({
  method : "post",
  body : "hello world",
});

我刚刚尝试了一些我认为可以工作的东西,这是一个更复杂的版本。

request({
  method : function(){
    return "post";
  },
  data: {'hello':'world'},
});

令我惊讶的是它不起作用。这也不是。

var m = function(){
  return "post";
};

request({
  method : m,
  data: {'hello':'world'},
});

我错过了什么吗?有没有办法让生成的函数进入这些对象?我会喜欢一些反馈。

3 个答案:

答案 0 :(得分:3)

您不想在此处传递函数,您希望传递其返回值。

request({
  method: (function() {
    return "post";
  })(),
  data: {'hello':'world'}
});

答案 1 :(得分:3)

您需要执行该函数并使用返回值,而不是函数本身。

var m = function(){
  return "post";
};

var data = function() {
  return {'hello':'world'};
}

request({
  method : m(),
  data: data()
});

答案 2 :(得分:0)

当文档加载时执行该函数,就像我在下面得到它一样。这将使m ='post'

var m = (function(){
  return "post";
})();

request({
  method : m,
  data: {'hello':'world'},
});