JavaScript - use is used to call a function, but 'this' is not set for the object passed as the first argument

I am trying to use the apply method to call the objectify function by passing an array of values ​​and using obj as an object. However, this not set to the object, but rather a global environment ( window ).

The purpose of this is to get an array of strings and then pass those strings to the objectify function. When a function is called, it takes array values, separates them, and if the object does not have a property with a string value, this 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); 

This task is set as window , not an obj object. How do I rewrite this code so that it sets obj as the value of this ?

The end result should be a modified obj object to become:

 obj = {user: {name: {firstname: 'John', lastname: 'Smith'}}}; 
+5
source share
1 answer

This (not a pun intended), because objectify is an "arrow function" that always uses this , which it inherits from the lexical domain, and will ignore anything passed through .apply or .call .

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

+2
source

Source: https://habr.com/ru/post/1259657/


All Articles