0

const small = {
  a: 1,
  func: function(b, c, d) {
    return this.a + b + c + d;
  },
};

const large = {
  a: 5,
};

small.func(2, 3, 5);

I need to access a: 5 from large object into small object. currently small.func(2,3,5) is giving 11 as output. I need to get 15 as ouput.

2
  • 1
    You can use .call() to bind the this to large Commented Jan 15, 2022 at 4:58
  • 1
    better to put the method outside of the object and then call it for any object you create. Commented Jan 15, 2022 at 5:10

2 Answers 2

1

Like this-

function func(b, c, d) {
    return this.a + b + c + d;
  }
const small = {
  a: 1,
  
};

const large = {
  a: 5,
};

func.call(large, 2,3, 5)
Sign up to request clarification or add additional context in comments.

Comments

1

You can either use call or apply here as:

const result = small.func.call(large, 2, 3, 5);

What above statement means is that You are taking the function(or can say borrowing) small.func function and applying in the context of large object with argument 2, 3, 5.

const small = {
  a: 1,
  func: function(b, c, d) {
    return this.a + b + c + d;
  },
};

const large = {
  a: 5,
};

   const result = small.func.call(large, 2, 3, 5);
// const result = small.func.apply(large, [2, 3, 5]);
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.