JavaScript: Context Handling

context


๐Ÿ’Ž Understanding this - call, apply, and bind

๐Ÿ‘‡ Intro: Why Does `this` Change Depending on How I Call a Function?

You copy a method from one object to another and suddenly this is undefined. Or you use a callback and this no longer points where you expected. These are all about how a function is called, not where it's written.

That’s where call, apply, and bind come in—they let you explicitly control the value of this. Once you understand this trio, those weird bugs suddenly make sense.

๐Ÿง  What is `this` in JavaScript?

this refers to the object that is calling the function or the context where a piece of code, such as a function's body, is supposed to run.

๐Ÿงช How does this context changes?

  • When used within a method of an object, this points to that object.
  • When method of an object is used as a callback to another function, it can lose its context and becomes undefined.
  • When used by itself, this points to the global object.
  • Within a function, this typically points to the global object.
  • When used in the arrow function then this has lexical scope.
  • In a function under strict mode, this becomes undefined.
  • During an event, this points to the element that triggered the event.
  • Methods such as call(), apply(), and bind() can reassign this to any desired object.

Interview:

Q: Why doesn't this works in a callback?

๐Ÿ’ป Example:

>>> this context

๐Ÿง  What are call(), apply() and bind() ?

call(): The call method is basically used to invoke the function with different this object. With the help of the call method, we can invoke a particular function with different objects.

apply(): Similar to call() method. The only difference is call() method takes the arguments separated by a comma while apply() method takes the array of arguments.

bind(): The bind method creates a new function based on the function on which it is called. Using the bind() method, we can preconfigure this keyword and arguments for the function.

Interview:

Q: How does call, apply and bind helps in handling this context?

๐Ÿ’ป Example:

>>> call, apply & bind context


Coming up next: Memory management in JavaScript >>>

Comments

Popular