This resolves Dynamically in JavaScript!
This cares about how a function was called, which shows how closely related this mechanism is to the idea of dynamic scoping.
JavaScript this mechanism is not actually that advanced, but developers often paraphrase that quote in their own mind by inserting complex or confusing, and there’s no question that without lack of clear understanding, his can seem downright magical in your confusion.
If the how of this snippet confuses you, don’t worry! We’ll get to that shortly. Just
set those questions aside briefly so we can look into the why more clearly.This code snippet allows the identify() and speak() functions to be re-used against multiple
context (me and you) objects, rather than needing a separate version of the function for each
object.Instead of relying on this, you could have explicitly passed in a context object to both
identify() and speak().
Description !!
We said earlier that this is not an author-time binding but a runtime binding. It is contextual based on the conditions of the function’s invocation. this binding has nothing to do with where a function is declared but has instead everything to do with the manner in which the function is called.
When a function is invoked, an activation record, otherwise known as an execution context, is created. This record contains information about where the function was called from (the call-stack), how the function was invoked, what parameters were passed, etc. One of the properties of this record is this reference which will be used for the duration of that function’s execution.
Let’s examine how this variation works. We create a function
bar()
which, internally, manually callsfoo.call(obj)
, thereby forcibly invokingfoo
withobj
binding forthis
. No matter how you later invoke the functionbar
, it will always manually invokefoo
withobj
. This binding is both explicit and strong, so we call it hard binding.
Conclusion !!
This cares about how a function was called, which shows how closely related this mechanism is to the idea of dynamic scoping.it only matters from where and how the function will be called.