gpt4 book ai didi

Javascript未捕获类型错误无法设置未定义的属性 '0'

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

此代码给出了 UNCAUGHT TYPE ERROR:CANNOT SET PROPERTY '0' OF UNDEFINED(..)为什么会出现这样的错误?

function node() {
this.parent = null;
this.children = [];
}
node.prototype.m = function () {
var insertchild = function (parent, child) {
var i;
if (typeof this.children === "undefined")
i = 0;
else
i = this.children.length;
this.parent = parent;
this.children[i] = child;
console.log(parent + " " + child);
}
return insertchild;
}
var n = new node();
n.m()('A', 'B');

最佳答案

问题出在 insertchild 函数内的 this

一种解决方案:

function node() {
this.parent = null;
this.children = [];
}
node.prototype.m = function() {
var insertchild = function(parent, child) {
var i = this.children.length;
// next four lines are not required
//if (typeof this.children === "undefined")
// i = 0;
//else
// i = this.children.length;
this.parent = parent;
this.children[i] = child;
console.log(parent + " " + child);
}
return insertchild.bind(this); // fix is here
}
var n = new node();
n.m()('A', 'B');

如果您处于没有 .bind() 方法的环境中

function node() {
this.parent = null;
this.children = [];
}
node.prototype.m = function() {
var me = this;
var insertchild = function(parent, child) {
var i = me.children.length;
me.parent = parent;
me.children[i] = child;
console.log(parent + " " + child);
}
return insertchild;
}
var n = new node();
n.m()('A', 'B');

我认为

关于Javascript未捕获类型错误无法设置未定义的属性 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31364859/

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