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

Javascript uncaught type error cannot set property '0' of undefined

本文关键字:属性 定义 设置 类型 错误 Javascript      更新时间:2023-09-26

这段代码给出了一个未捕获的类型错误: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');
我认为

在函数insertChild()中,this关键字引用自身的函数作用域,而不是外部作用域(您想要的节点实例)

insertChild()函数作用域中,this关键字不指向node实例。它引用的是insertChild()的函数作用域。

快速修复

由于在insertChild()函数中引用this不会引用node实例,因此您可以通过将this变量委托给其他变量(例如self)来轻松处理此问题,因此您仍然可以在insertChild()函数中保留对它的引用。

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