-1

I have several objects constructed by object literals:

let obj1={
    list: [],
    a() {},
    b() {},
};
let obj2={
    list: [],
    c() {},
    d() {},
};

Now I want to attach a common method to all objects, say

const f=()=>console.log(this.list);

But If I do

obj1.f=f; obj2.f=f;

And try to run it, it will give undefined.

How to do this so that this can correspond to the object?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

1 Answers1

1

You need to have a non-arrow function and then it will work as below:

let obj1={
    list: [],
    a() {},
    b() {},
};
let obj2={
    list: [],
    c() {},
    d() {},
};

const f=function() {console.log(this.list);}
obj1.f=f; 
obj2.f=f;

console.log(obj1);
console.log(obj2)
Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20