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

时间:2015-07-12 05:57:40

标签: javascript

此代码给出了一个UNCAUGHT TYPE ERROR:无法设置'0'未定义的属性(..) 为什么会出现这样的错误?

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');

2 个答案:

答案 0 :(得分:1)

问题在于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');

我认为

答案 1 :(得分:0)

在函数insertChild()中,this关键字指的是自身的函数范围,而不是外部范围(节点的实例)

如果您处于函数insertChild()的范围内,则this关键字不会引用node实例。它改为引用insertChild()的函数范围。

快速修复

由于在this函数中引用insertChild()不会引用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');