JavaScript - 使用 apply 调用函数,但 'this' 未设置为作为第一个参数传递的对象

JavaScript - using apply to invoke function, but 'this' is not being set to the object passed as first argument

我正在尝试使用 apply 方法调用 objectify 函数,传递一个值数组并使用 obj 作为对象。但是,this 并未设置为对象,而是设置为全局环境 (window)。

这样做的目的是获取一个字符串数组,然后将这些字符串传递给函数objectify。调用该函数时,它获取数组值,将它们拆分,如果对象没有 属性 和字符串值,则会创建 属性。

下面是代码:

let obj = {};
let arr = ["user.name.firstname=John", "user.name.lastname=Smith"];

const objectify = x => {
let cur = this, v;
return x.split('.').forEach(e => /=/g.test(e) ?
(v = e.split('='), cur[v[0]] = v[1]) : cur[e] ?
cur = cur[e] : (cur[e] = {}, cur = cur[e]))};

objectify.apply(obj,arr);

问题是 this 被设置为 Window 而不是对象 obj。我应该如何重写此代码,以便将 obj 设置为 this 值?

最终结果应该是修改后的 obj 对象,因此它变成:

obj = {user: {name: {firstname: 'John', lastname: 'Smith'}}};

这(没有双关语意)正在发生,因为 objectify 是一个 "arrow function",它始终使用它从词法范围继承的 this,并且将忽略通过 .apply.call.

如果您将其重写为普通函数,它应该可以正常工作。