Search code examples
javascript-objects

Not able to understand Javascript object behavior


I am confused by the following behavior in JS. I am declaring a javascript object in two ways

Lets say employee.json = [{emp1}]

1)

const data = {
    employees : require('../Model/employee.json') ,
    setEmployee : function(data){ 
        this.employees = data;
    }
};
  1. const data = {}; data.employees = require('../Model/employee.json'); data.setEmployee = (data) => { this.employees = data; }

now if if i pass any array of employees to setemployee like

data.setEmployee([{emp1},{emp2}]); data.employees // returns the updated list [{emp1},{emp2}]) if i use method 1 and returns the original list [{emp1}]) if i use method 2 of definition


Solution

  • This happens due to arrow function in js does't have it's own this reference it always inherit from the parent scope (lexical scoping).

    in 2nd method replacing arrow function with normal function definition will fix the issue

    const data = {}; 
    data.employees = require('../Model/employee.json'); 
    data.setEmployee = function (data){ this.employees = data; }