avalanche1
avalanche1

Reputation: 3592

js - access parent object after attaching a property to it

obj = {foo: 'foo'}

obj2 = {
  bar: ()=> console.log(this.foo)
}

obj.bar = obj2.bar

obj.bar()

What can I do to make obj.bar() produce 'foo'?

Essentially, what I'm trying to do is to create an object and some time later attach a method to it that will be able to access data in the original object.

Update
What if I have multiple methods in obj2 and want to add them as a group to obj1? Then the solution for the 1st situation will not suit.

obj = {foo: 'foo'}

obj2 = {
  bar: function() {
    console.log(this.foo);
  },
  baz: function() {
    return smth();
  },
  etc: function() {
    return smth();
  }
};

obj.barMethods = obj2;

obj.barMethods.bar();

Upvotes: 0

Views: 39

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42480

Use the classic function syntax instead of an arrow function:

obj = {foo: 'foo'}

obj2 = {
  bar: function() { console.log(this.foo) }
}

obj.bar = obj2.bar

obj.bar() // "foo"


An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Source, emphasis mine

Upvotes: 1

Related Questions