gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:05:23 25 4
gpt4 key购买 nike

也许你会发现问题所在。控制台总是显示:

类型错误: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");
}
}

最佳答案

您需要在调用函数之前定义该函数:

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

您现在可能已经意识到,对象上的方法函数不会被提升,因此您会收到所看到的错误。

关于javascript - JS : TypeError: this. _init 不是函数。 (在 'this._init()' 中, 'this._init' 未定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com