Mike S. Mike S. - 1 year ago 62
Javascript Question

Passing JavaScript function to another function within object loses object variable scope

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() {
testAgain(updater) {
updateUID(id) {
this.uid = id;

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

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

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.

Answer Source

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() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download