【问题标题】:JS: TypeError: this._init is not a function. (In 'this._init()', 'this._init' is undefined)JS:TypeError:this._init 不是函数。 (在 'this._init()' 中,'this._init' 未定义)
【发布时间】:2015-10-02 01:22:46
【问题描述】:

也许你会发现问题。控制台总是说:

TypeError:this._init 不是函数。 (在 'this._init()' 中,'this._init' 是未定义的)

nodes = [];
for (var i = 0; i < 3; i++) {
    var newNode = new Node(i*100,0);
    nodes.push(newNode);
};

function Node(posX, posY, parent) {
    if (typeof parent === 'undefined') { parent = 0; }
    this.parent = parent;
    this.children = [];
    this.text = "Node";
    this.posX = posX;
    this.posY = posY;
    this._init();

    this._init = function() {
        alert("test");
    }
}

【问题讨论】:

  • 为什么应该是函数?您在尝试调用它之后定义它。函数表达式没有被提升。

标签: javascript class oop typeerror


【解决方案1】:

你需要在调用它之前定义函数:

function Node(posX, posY, parent) {
    if (typeof parent === 'undefined') { parent = 0; }
    this.parent = parent;
    this.children = [];
    this.text = "Node";
    this.posX = posX;
    this.posY = posY;

    this._init = function() {
        alert("test");
    }

    this._init();   
}

http://jsfiddle.net/4wsLhd8y/

如果您在其他地方定义之前调用了函数,您可能会对此感到困惑。在某些情况下,您的功能可能会被“提升” 到脚本的顶部。下面显示了一个完全合法的调用:

isItHoisted();

function isItHoisted() {
    console.log("Yes!");
}

http://adripofjavascript.com/blog/drips/variable-and-function-hoisting

您现在可能已经知道,对象上的方法函数没有被提升,所以您会得到您所看到的错误。

【讨论】:

  • 我有另一个脚本可以运行,即使函数是在调用之后定义的!
  • @Hustensaft 添加了更多上下文。
【解决方案2】:

看起来你在定义它之前调用了 _init。

this._init = function() {
   alert('test');
}

this._init();

【讨论】:

  • 我有另一个脚本可以运行,即使函数是在调用之后定义的!
  • 我不会依赖这种方法。 JS 提升是一件棘手的事情,并且在下一个版本中会发生变化,大部分情况下根本不允许。函数通常不会被提升。
  • 之后可以定义一个init-Method吗?例如Node.prototype = {...}?
  • 你可以覆盖方法,是的。因此,在初始设置之后(如上面我的示例所示),您可以再执行一次“this._init = function () {}” .这与良好的编码标准背道而驰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 2017-06-28
  • 2011-04-28
  • 2021-02-01
  • 1970-01-01
  • 2015-12-04
相关资源
最近更新 更多