![]() When we invoke a function in the context of an object that owns or contains the function’s this, it will point to that object.Ĭonsider the following example: function sayHello ( ) let a = obj. ![]() Understanding these four ways can help us understand how the this keyword gets bound. The four rules for binding this are determinedīy how we invoke functions in JavaScript. In JavaScript, there are four different ways to invoke a function, and each one of them provides different context objects for the this keyword to point at when executing a function. How then can we determine what the value of this points at for any given function? 4 Rules for Binding ‘This’ It always points to a context object that can be identified by looking at the call site of a function. The this keyword never points at the function itself. The this keyword can be used to invoke functions in different contexts, and depending on the context, this might mean something entirely different every time. So, for every function invocation, there is a special identifier called this, but this isn’t concerned with where a function is defined instead, it is interested in how it is called. What this references is entirely determined by the call site (the location where a function is called, not where it is declared). The execution context contains a this reference or a this binding that will be used throughout the function’s execution. When you invoke a function in JavaScript, a new execution context is created and added to the call stack. As confusing as it can be, it is a fundamental concept because it allows for flexibility, reusing a function in It is one of the most common JavaScript keywords. In this article, we will look at what the this keyword is and the four rules that determine its behavior in JavaScript.Ĭompared to other languages, the this keyword acts differently in JavaScript.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |