2017-10-10 21 views
3

由於某種原因,從Google Apps腳本項目的服務器端返回的對象將任何成員函數替換爲null。下面是一些示例代碼演示此:來自Google Apps腳本的服務器的對象被刪除了成員函數

server.gs

function A() { 
    this.a = 'a string'; 
    this.toString = function() { return this.a; } 
    this.innerObj = { b : "B", toString : function(){ return 'inner object'; } } 
} 

function getA() { return new A(); } 

clientJS.html;/*或控制檯,如果印刷原料時更喜歡... */

google.script.run.withSuccessHandler(console.log).getA(); 

對象,看起來是這樣的:

{ "a": "a string", "toString": null, "innerObj": { "b": "B", "toString": null } } 

Live demo of the problem

我能做些什麼這個?!

回答

1

我的答案延伸了慾望的答案。我能得到這個工作,通過字符串化的成員函數,但對於重建,而不是使用eval(),我使用了這些:

function shouldBeFunction(str) 
{ 
    str = str.toString().trim(); 
    // str should *not* be function iff it doesn't start with 'function' 
    if (str.indexOf('function') !== 0) return false; 
    // str should *not* be function iff it doesn't have a '(' and a ')' 
    if ((str.indexOf('(') === -1) || (str.indexOf(')') === -1)) return false; 
    // str should *not* be function iff it doesn't have a '{' and a '}' 
    if ((str.indexOf('{') === -1) || (str.indexOf('}') === -1)) return false; 
    return true; 
} 

var myObjectWithFunctions = JSON.parse(objectWithStringsAsFunctions, 
    function (key, value) { 
     var DEBUG = false; 
     if ((typeof(value) === 'string') && (shouldBeFunction(value))) { 
      if (DEBUG) { 
       console.log('function string detected on property named : ' + key); 
       console.log('function text: " ' + value + '"'); 
      } 
      // get arguments list, if there is one to get 
      var argsList = value.substring(value.indexOf('(') + 1, value.indexOf(')')).trim(); 
      if (DEBUG) console.log('argsList == ' + argsList); 
      // get function body 
      var functionBody = value.substring(value.indexOf('{') + 1, value.lastIndexOf('}')).trim(); 
      if (DEBUG) console.log('functionBody == ' + functionBody); 
      if (argsList) 
       return new Function(argsList, functionBody);  
      return new Function(functionBody); 
     } 
     return value; 
    } 
); 

原因是,我不知道是否eval()是邪惡的,或錯誤的編程習慣的標誌。

更新:我瞭解到,eval() may be OK if the strings came from the server並正在變回功能,在客戶端

+0

**更新**:我瞭解到我的代碼實際上將所有函數字符串轉換爲匿名函數。 –

3

這是由設計,如所指出in the documentation

法律參數和返回值是JavaScript的基元等數值,布爾,字符串,或者爲空,以及JavaScript對象和陣列所構成的原語,對象和數組。 [...]如果您試圖傳遞除表單或其他禁止類型(包括對象或數組內的禁止類型)的日期,函數,DOM元素,則請求失敗。

作爲一種變通方法,您可以stringify an object with its methods

JSON.stringify(obj, function(key, value) { 
    if (typeof value === 'function') { 
    return value.toString(); 
    } else { 
    return value; 
    } 
}); 

,然後在接收端reconstruct the functions from strings

+0

感謝單挑!順便說一句,我擴大了你的答案。 –

相關問題