应用抛出错误 Cannot read 属性 of null

Apply is throwing an error of Cannot read property of null

在jstree插件中有这样一个函数:

this.check_node = function (obj, e) {
    if(this.settings.checkbox.tie_selection) { return this.select_node(obj, false, true, e); }
    // Removed code for readability
};

所以对于 check_node 我必须传递一个参数列表,我必须传递的参数列表在一个数组中,所以我做如下:

scope.jstree(true).check_node(...scope.args['check_node']);

其中 scope.args['check_node'] 包含我要传递给 check_node 的参数列表,使用扩展运算符执行此操作不会引发任何错误,但由于某种原因我无法使用 ES6语法,我坚持使用 ES5,所以我不得不使用 apply 代替如下:

scope.jstree(true).check_node.apply(null, scope.args['check_node']);

但这会抛出以下错误:

TypeError: Cannot read property 'settings' of null

在这一行中:

if(this.settings.checkbox.tie_selection)

为什么在这种情况下 apply 会抛出错误而 spread oprator 却不会?我该如何解决这个问题?

好吧,在您的 ES5 代码中,您显式地为 thisArg 传递了 null,因此 this 是被调用函数中的 null。这里不足为奇。

扩展运算符只是简单地扩展数组,就像您自己传递数组的值一样。

因为您通过传递 null 作为第一个参数来明确表示 "Make this during the function call null"。

您需要传递您想要的值 this 作为第一个参数。

我不熟悉你的图书馆,但这样做就可以了:

var obj = scope.jstree(true);
obj.check_node.apply(obj, scope.args['check_node']);

如果jstree returns scope,虽然,你可以避免变量:

scope.jstree(true).check_node.apply(scope, scope.args['check_node']);

因为您正在使用 null.The 更改 check_node 的第一个参数, apply 采用的第一个参数是 object/context,它应该作为您调用的函数的 this。