-1

Is it possible to detach functions in javascript while allowing them to retain access to their context?

For example suppose we have a ViewportScroller instance called vc. We can get the current scroll position by calling:

vc.getScrollPosition()

Is it possible to detach it like this:

cont scrollPosition = vc.getScrollPosition

While ensuring that it will still work and be able to access everything it needs to work or do we always need to wrap vc like this:

const scrollPostion = ()=>vc.getScrollPosition()
Ole
  • 29,797
  • 32
  • 110
  • 232
  • 1
    `let scrollPostion = vc.getScrollPosition.bind(vc)`. See [*How does the “this” keyword work?*](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) and [*What is the use of the JavaScript 'bind' method?*](https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method) – RobG Dec 14 '19 at 21:12
  • Does this answer your question? [What is the use of the JavaScript 'bind' method?](https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method) – Dexygen Dec 14 '19 at 21:23

1 Answers1

2

You can also use .bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

cont scrollPosition = vc.getScrollPosition.bind(vc)
Marcos Casagrande
  • 29,440
  • 5
  • 62
  • 77