Javascript对象无法识别功能

时间:2016-01-31 04:53:06

标签: javascript

我有一个Javascript类定义如下:

function Node(init, parent) {
  this.value = init;
  this.children = [];
  this.updateChildren(this.value);
}

Node.prototype.updateChildren = function(value) {
  this.children.push(value);
 };

当我运行它时...我收到错误,

this.updateChildren() is not defined.

我在这里缺少什么线索?

完整代码:



'use strict';

var millionNumbers = [];

for (var i = 2; i< 1000000; i++) {
  if (!millionNumbers[i]) {
    millionNumbers[i] = new Node(i, null);
  }
}

function Node(init, parent) {
  this.value = init;
  this.children = [];
  if (parent) {
    this.parent = parent;
  }
  var newValue;
  
  if (isEven(this.value)) {
    newValue = this.value/2;
  } else {
    newValue = (this.value * 3) + 1;
  }

  //whether newValue is 1 or something else, we still have add it to the children list
  this.updateChildren(newValue);

  if (millionNumbers[newValue]) {
    var chainedNode = millionNumbers[newValue];
    this.children.concat(chainedNode.children);
  }

  if (newValue === 1) {
    this.endChain();
  } else {
    new Node(newValue, this);
  }

}

Node.prototype.updateChildren = function(value) {
  this.children.push(value);
  if(this.parent) {
    this.parent.updateChildren(value);
  }
};

Node.prototype.endChain = function() {
    if (!millionNumbers[this.value]) {
      millionNumbers[this.value] = this;
      this.parent = null;
    }
  };
  
function isEven(value) {

  if (value % 2 === 0) {
    return true;
  } else {
    return false;
  }
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

for循环在设置Node.prototype.updateChildren之前实例化Node对象,因此在Node构造函数中,this.updateChildren仍未定义。

要解决此问题,只需将for循环移动到文件末尾即可。

另外:对于Collat​​z猜想,祝你好运!

答案 1 :(得分:-1)

认为你是在调用这些类而不先定义它们。 你可以这样试试:

 function updateChildren(value) {
  this.children.push(value);
 };

function Node(init, parent) {
  this.value = init;
  this.children = [];
  this.updateChildren(value);
}

Node.prototype.updateChildren(value);