Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to use the apply method to invoke the objectify function, passing an array of values and using obj as the object. However, this is not being set to the object, but rather the global environment (window).

The purpose of this is to get an array of strings, then pass those strings to the function objectify. When the function is invoked, it takes the array values, splits them, and, if the object does not have a property with the string value, that property is created.

Here is the code below:

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

The problem is this is set as Window rather than the object obj. How should I rewrite this code so that it sets obj as the this value?

The end result should be a modified obj object so it becomes:

obj = {user: {name: {firstname: 'John', lastname: 'Smith'}}};
like image 829
docgunthrop Avatar asked Oct 30 '22 17:10

docgunthrop


1 Answers

This (no pun intended) is happening because objectify is an "arrow function" that always uses the this that it inherits from the lexical scope, and will ignore any passed via .apply or .call.

If you rewrite it as a normal function it should work as desired.

like image 176
Alnitak Avatar answered Nov 09 '22 23:11

Alnitak