What 10x JavaScript Developers Know About ‘this’
source link: https://blog.bitsrc.io/what-javascript-10x-developers-know-about-this-object-408f467f0497
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
What 10x JavaScript Developers Know About ‘this’
Photo by Irvan Smith on Unsplash
Understanding these concepts will save you a lot of time debugging tricky issues in JavaScript.
JavaScript this
object is one of the most commonly used concept of JavaScript. It is quite useful to understand how it works internally.
Runtime binding
In JavaScript the scope of this
inside a function is determined at runtime. The scope of this
change depending on how that function was called no matter how it was defined.
Whenever a JavaScript function is invoked the runtime binding of this
comes into play. The this
will have information such as: call-stack, parameters passed, etc.
It is important to remember that the function call-site is used determine the binding of this
during the execution of a function.
figure 2
In above code, the variable a
is declared in global scope. When the function foo
is called, this.a
resolves to variable a
in global scope.
figure 3
In above example, the output is undefined
because the variable a
is not defined in global scope. This is why it is not accessible in function foo
.
It is important to note that the global object is only eligible for the default binding of this
. It is important that this
is not attached to global object when strict mode is enabled.
figure 4
It is important to remember that the strict mode of the cal-site of the function is irrelevant to the other function.
figure 5
Implicit Binding
The scope of this
can be implicitly defined by calling the function inside an object.
figure 6
It is important to remember that if there is nesting objects, then only the closest object property value will be available in function. It all goes down to what is the call-site of the function actually.
figure 7
figure 8
figure 9
figure 10
Explicit Binding
JavaScript provides two utilities: call
and apply
for explicitly binding of scope of this
.
figure 11
Play around
this
and JavaScript and have fun with it. The concept aroundthis
is often asked in interviews. Have fun learning JavaScript!.
Read this post and more on my Typeshare Social Blog
Go composable: Build apps faster like Lego
Bit is an open-source tool for building apps in a modular and collaborative way. Go composable to ship faster, more consistently, and easily scale.
Build apps, pages, user-experiences and UIs as standalone components. Use them to compose new apps and experiences faster. Bring any framework and tool into your workflow. Share, reuse, and collaborate to build together.
Help your team with:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK