2014-09-30 68 views
0

我在學習javascript。作爲這一努力的一部分,我寫了一個基本的極小極大AI。我有以下幾種方法:JavaScript方法不明確

Computer.prototype.expand = function(node) { 
    /* adds all state action pairs to the node.successors array */ 
}; 

Computer.prototype.getMove = function(boardAr) { 
    console.log("getMove"); 
    var b2 = boardAr.slice(); 
    var i; 
    var action; 

    this.root = new TNode(b2, this.mark); 
    this.root.AIPlayedLast = false; 
    this.expand(this.root); 
    this.root.successors.forEach(this.minVal); 
    action = maxNode(root.successors); 
    this.draw(action); 
    registerMove(action, this.mark); 
}; 

Computer.prototype.minVal = function(node) { 
    if (node.isTerminal) { 
    return; 
    } else { 
    this.expand(node); 
    node.successors.forEach(maxVal); 
    node.utility = this.minNode(node.successors).utility; 
    } 
}; 

getMove方法被調用的後續調用expand去預期。但是,從minVal方法調用expand時,我得到:Uncaught TypeError: undefined is not a function。我完全被這個困惑了。任何幫助/建議將不勝感激。

+0

不知道,但據我所知,你應該以一個分號結束每一個功能,所以之後的每個}你應該增加; - 編輯:測試過,但不會有太大變化,只有幾個語法錯誤會消失 – briosheje 2014-09-30 08:47:07

+0

乍一看,這看起來很好(儘管如果你正在編寫很多這種類型的代碼,你可能想看看組合構造函數它提供了一個更加整潔的書寫方式 - http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/),所以問題可能出現在代碼被調用的方式中? – glenatron 2014-09-30 08:50:45

+0

你可以請創建一個小提琴來重現這個問題嗎? – thefourtheye 2014-09-30 08:51:45

回答

3

我想原因是該行中:

this.root.successors.forEach(this.minVal); 

您傳遞MINVAL如無環境基準,它不會在您的計算機實例的上下文中調用(這)

這裏是你如何可以改善它:

var self = this; 
this.root.successors.forEach(function() { 
    self.minVal.apply(self,arguments); 
}) 
0

forEach()方法可能會被調用的每個後繼者。所以,你傳遞Computer :: minVal方法(this.minVal),但是用TNode(?)作爲這個指針。嘗試:

var that = this; 
this.root.successors.forEach(function(node) { 
that.minVal(node)); 
}); 
2

最簡單,最快的解決辦法只是改變

this.root.successors.forEach(this.minVal); 

this.root.successors.forEach(this.minVal.bind(this)) 

這解決了同其他的答案的問題,但在某種程度上有些可能會考慮更緊湊。

或者,你可以通過一個「本」的forEach函數作爲第二個參數的forEach有點未充分利用的功能:

this.root.successors.forEach(this.minVal, this) 

此功能也可在該採取其他Array原型方法函數,包括map,filter,some,every(但不是reducereduceRight)。

ES6箭頭函數處理this不同,所以你可以做

this.root.successors(forEach(e => this.minVal(e)));