Javascript,在对象文字中传递函数,它是可调用的吗

Javascript, passing a function in an object literal and is it callable?

本文关键字:调用 传递函数 对象 文字 Javascript      更新时间:2023-09-26

在学习Javascript和修改一个很酷的自动完成库的过程中,我现在站在了这个前面:

我需要检查在对象文字中传递的东西是一个变量/字段(被认为是一个简单的值(还是可以调用的东西。

(由于我的自动完成依赖于许多输入字段,我需要在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//here i’m lost…",而不是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 );

您可以执行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;  
    }
}
   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') {
          }
       }
  }