0

I have a 3rd-party library that performs Facebook authentication and I need to pass it a callback handler. This works fine, but in the callback function it cannot set other params of the object.

I created this simple test and need help to understand why the 3rd case does not work, to simulate what is happening in my app.

const Test = {
 uid: null,
 test() {
    this.testAgain(this.updateUID);
 },
 testAgain(updater) {
   updater(7);
 },
 updateUID(id) {
   this.uid = id;
 }
};

alert(Test.uid); // expect null, got null

Test.updateUID(3);
alert(Test.uid); // expect 3, got 3

Test.test();
alert(Test.uid); // expect 7, got 3 ???

I appreciate suggestions on how to get the 3rd case to work. I have to pass the function to the Facebook auth library and when FB calls that function, it needs to be able to update params of the object.

0

1 Answer 1

2

When you pass that method in as an argument the reference to the object gets 'stripped' so to speak. So when you are setting this.uid, it's setting a property on an object that is no longer 'Test'. To keep the reference you can use bind

test() {
  this.testAgain(this.updateUID.bind(this));
},
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thanks. I will accept answer in 5 minutes when it allows me.

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.