簡體   English   中英

是否可以在其內部遞歸調用對象屬性(即函數)?

[英]Can an objects property, which is a function, be recursively called within itself?

嘗試遞歸調用對象中的setTestType函數時,我不斷收到錯誤消息“ Uncaught TypeError:this.setTestType不是函數”。

將函數定義為對象屬性並嘗試調用自身時,是否不允許遞歸?

 var resultGaAuto = [{ bestPracticeID: "344033" }]; var resultAuto = [{ bestPracticeID: "111111" }]; var AST = { handleSave: function() { var data = {}; var gaRecords = this.processResults(resultGaAuto); var autoRecords = this.processResults(resultAuto); //console.log(gaRecords); //console.log(autoRecords) var testTypeGaRecords = this.setTestType(gaRecords, 5); var testTypeAutoRecords = this.setTestType(autoRecords, 4); console.log(testTypeGaRecords); data.records = Object.assign({}, testTypeGaRecords, testTypeAutoRecords); console.log(data); }, setTestType: function(obj, num) { Object.keys(obj).forEach(function(key) { if (key === "testResult") { return (obj[key] = num); } //*******ERROR******* return this.setTestType(obj[key], num); }); }, processResults: function(results) { var records = {}; $.each(results, function(i, result) { records[result.bestPracticeID] = records[result.bestPracticeID] || { violation: { violationID: result.bestPracticeID }, instances: [] }; records[result.bestPracticeID].instances.push({ lineNumber: 1, element: "testEl", attribute: "testAttr", xpath: "testPath", testResult: 3 }); }); return records; } }; AST.handleSave(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

是否可以在其內部遞歸調用對象屬性(即函數)?

是。 這里沒有技術限制。 只是不正​​確的代碼。

未捕獲的TypeError:this.setTestType不是一個函數

this是錯誤的。

固定

setTestType: function(obj, num) {
Object.keys(obj).forEach(function(key) {
  if (key === "testResult") {
    return (obj[key] = num);
  }
  //*******FIXED*******
  return AST.setTestType(obj[key], num);
});
},

更多

閱讀上thishttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

您的匿名函數的綁定上下文應為AST

setTestType: function(obj, num) {
Object.keys(obj).forEach(function(key) {
  if (key === "testResult") {
    return (obj[key] = num);
  }
  //*******ERROR*******
  return this.setTestType(obj[key], num);
}.bind(AST)); // see the bound context!
}

暫無
暫無

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

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