0

I tried to execute this small part of code in my browser console:

a = {b: 1}
Object.defineProperty(a, 'b', { get: function() { console.log(5); } })
c = a.b
c
c

Everytime i used to call 'c' varaible, i am not getting console.log(5) to be executed. That means my getter is not calling. I think that might be because i am not calling a.b directly but using c variable instead. Can someone confirm/reject my thoughts ? Also how can i make it call getter everytime i am calling 'c' ?

Thanks.

1
  • You have a.b assigned to c. That is when your getter in invoked. And once the get value is assigned to c. c behaves like any other variable. Commented Nov 21, 2017 at 16:22

2 Answers 2

2

Can someone confirm/reject my thoughts

You will get console.log(5) run every time when you call a.b. But when you use c = a.b, this runs the getter function, copies the result into the c (which is undefined) and starting from here c has its independent value which is returned via a.b. So after this every time when you call c, you evaluate c and get the value of it, not the a.b. In few words c has nothing anymore with a.b.

Also how can i make it call getter everytime i am calling 'c' ?

Actually there is no solution. One thing you can do is returning a function which logs the result, but now you will need to invoke c to get it work. Maybe you can chagne your logic in somewhere, so this is not a good workaround.

const a = {b: 1}
Object.defineProperty(a, 'b', { get: function() { 
      console.log(5); 
      return () => console.log(5);
   } 
});
const c = a.b;
c();
c();

Sign up to request clarification or add additional context in comments.

Comments

0

You're only getting b once, and assigning the returned value, in this case undefined, to c.

The getter is not called anymore if you work with c after that.

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.