2017-08-09 39 views
0

當我試圖在我的對象中遞歸調用setTestType函數時,我總是收到一個錯誤「Uncaught TypeError:this.setTestType is not a function」。作爲函數的對象屬性可以在其內部遞歸調用嗎?

將函數定義爲對象屬性並嘗試自行調用時,不允許遞歸嗎?

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>

+0

你不叫它從本身,你試圖在'forEach'回調中調用它。你也不能'返回',順便說一句 - 只是使用正常的循環! – Bergi

回答

0

您的匿名函數的約束範圍內應該是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! 
} 
+0

您也可以使用ES6箭頭函數或嘗試綁定'this'對象 – Wartoshika

0

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

是。這裏沒有技術限制。只是錯誤的代碼。

Uncaught TypeError: this.setTestType is not a function

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); 
}); 
}, 

更多

this讀了起來:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

相關問題