Javascript,在对象文字中传递函数并且可以调用吗?

时间:2011-10-20 14:15:24

标签: javascript function call

总是在学习Javascript和修改一个很酷的autocomplete library的过程中,我现在面前这个:

我需要检查对象文字中传递的内容是否是变量/字段(可以被视为简单值),或者是否可以调用。

(因为我的自动完成依赖于许多输入字段,我需要在Ajax.Request之前“重视”正确的事情)以便这个声明(参见'额外'部分...)

   myAutoComplete = new Autocomplete('query', {
        serviceUrl:'autoComplete.rails',
    minChars:3,
    maxHeight:400,
    width:300,
    deferRequestBy:100,
    // callback function:
    onSelect: function(value, data){
                alert('You selected: ' + value + ', ' + data);
                       }
            // the lines below are the extra part that i add to the library
            //     an optional parameter, that will handle others arguments to pass
            //     if needed, these must be value-ed just before the Ajax Request... 
    , extraParametersForAjaxRequest : { 
                  myExtraID : function() { return document.getElementById('myExtraID').value; } 
    }

在下面看到“1 //这里我迷路了......”而不是1 =>我想检查一下,如果extraParametersForAjaxRequest [x]是否可调用,如果是,则调用它,如果不是,则仅保留其值。所以,我得到了我的其他输入的正确价值......同时保持一个非常通用的方法和清理修改这个库......

{
  var ajaxOptions = {
    parameters: { query: this.currentValue , },
    onComplete: this.processResponse.bind(this),
    method: 'get'
  };
  if (this.options.hasOwnProperty('extraParametersForAjaxRequest'))
  {
      for (var x in this.options.extraParametersForAjaxRequest)
      {
          ajaxOptions.parameters[x] = 1 // here i'm lost...
      }
  }


  new Ajax.Request(this.serviceUrl, ajaxOptions );

2 个答案:

答案 0 :(得分:2)

   if (typeof this.options.extraParametersForAjaxRequest[x]==='function') {

   }

你也应该这样做:

   if (this.options.extraParametersForAjaxRequest.hasOwnProperty(x) {
       if (typeof this.options.extraParametersForAjaxRequest[x]==='function') {

       }
   }

在迭代对象的属性时,否则你最终也会看到原型成员。

另一个建议是使用您正在处理的事物的别名使其更具可读性。所以最终将是:

  var opts = this.options.extraParametersForAjaxRequest;
  // don't need to check for existence of property explicitly with hasOwnProperty
  // just try to access it, and check to see if the result is
  // truthy. if extraParametersForAjaxRequest isn't there, no error will
  //  result and "opts" will just be undefined
  if (opts)
  {
      for (var x in opts) {
          if (opts.hasOwnProperty(x) && typeof opts[x]==='function') {

          }
       }
  }

答案 1 :(得分:2)

您可以执行typeof以查看参数是否为函数,如果是,则调用它。

var value;
for (var x in this.options.extraParametersForAjaxRequest)
{
    value = this.options.extraParametersForAjaxRequest[x];

    if (typeof(value) == 'function') {
        ajaxOptions.parameters[x] = value();
    }
    else {
        ajaxOptions.parameters[x] = value;  
    }
}