2014-09-30 49 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)));