2010-09-10 64 views
0

我是JavaScript新手,面向對象程序設計請耐心等待我的任何含糊之處。處理對象參數

我有一個方法,需要一個對象作爲它的參數。 所需的對象爲該方法設置選項。

var objInstance = csvObj.getData({ 
    url: '', // csv url 

    format: '', // return data format 

    onComplete: function (output) { 
      // a function that will display data returned 
    } 
}); 

csvObj如下

var csvObj = { 
    getData: function (o) { 

     var format = o.format || 'json', //optional options 
      url = o.url, callback = o.onComplete; // required options 

     function include_js(jsurl) { // private function for performing cross dormain requests 
      var script = document.createElement("script"); 
      script.type = "text/javascript"; 

      script.src = jsurl; 
      document.getElementsByTagName("head")[0].appendChild(script); 
     } 


     (function() { // anonymous function for proccessing and returning data 

      if (typeof callback === 'function' && url) { // if require options are defined 

       if (!window.call_back) { // and global call_back function is not yet defined 
        window.call_back = callback; // define global call_back function (will be called when external script is loaded) 
       } 

       var restQuery = 'http://query.yahooapis.com/v1/public/yql?q=', 
       query = 'select * from csv where url="' + url + '" and columns="' + cols + '"', 

       yqlQuery = restQuery + encodeURIComponent(query) + '&format=' + data + '&callback=call_back'; // create YQL query 
       include_js(yqlQuery); // create a cross dormain YQL request 
      } 
     else { 
       alert('onComplete function or csv url not defined.'); // required options not defined 
      } 
     }()); 

    } 
}; 

問題定義:是否有處理對象參數不是簡單地訪問這樣一個更好的辦法:

var privateProperty = object.property;

var privateMethod = object.method; 

回答

2

你的方法是完全有效的。你可以像這樣做,太:

var privateMethod = object['method']; 

這可以是動態獲取屬性很方便,但總的來說,我喜歡object.method,因爲它更容易閱讀。

+0

+1 928我想我可以相信你的答案。 – 2010-09-10 14:05:09