簡體   English   中英

Javascript,在對象文字中傳遞函數並且可以調用嗎?

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

總是在學習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 //這里我迷路了......”而不是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 );
   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') {

          }
       }
  }

您可以執行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;  
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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