JavaScript方法未定义

JavaScript method is undefined

本文关键字:未定义 方法 JavaScript      更新时间:2023-09-26

我正在努力学习JavaScript。作为这项工作的一部分,我正在编写一个基本的minimax AI。我有以下方法:

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时,我得到:

未捕获的类型错误:undefined不是函数。

我对此感到非常困惑。如有任何帮助/建议,我们将不胜感激。

我认为原因在这一行:

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

您将minVal作为无上下文引用传递,它将不会在您的计算机实例(此)的上下文中调用

以下是您可以改进的方法:

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

最简单、最快捷的解决方案就是更改

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

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

这与其他答案一样解决了问题,但在某种程度上,有些人可能会认为它更紧凑。

或者,您可以将"this"作为第二个参数传递给forEach函数,这是forEach:的一个使用不足的特性

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

此功能也可用于其他采用函数的Array原型方法,包括mapfiltersomeevery(但不包括reducereduceRight)。

ES6箭头功能处理this的方式不同,因此您可以执行

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

forEach()方法可能会为每个继承者调用。因此,您传递Computer::minVal方法(this.minVal),但使用TNode(?)作为此指针。尝试:

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