當我試圖在我的對象中遞歸調用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>
你不叫它從本身,你試圖在'forEach'回調中調用它。你也不能'返回',順便說一句 - 只是使用正常的循環! – Bergi