What You Should Know About “this” Keyword in JavaScript
The more you know, the fewer bugs you’ll have.
this in javascript always points to an object that is related to the environment in which the function is executed at runtime, i.e. it is dynamically bound to the environment in which the function is executed, not to the environment in which the function was declared.
There are many reasons why javascript is difficult to master, one of which is that this
sometimes doesn’t work the way we expect it to.
So I’ve summarized below a few scenarios where we’ll encounter this
in our work:
- Object method
- Function
- Constructor
- with
- eval
1. Object method
this
points to an object when a function is called as a method of that object.
The age
declaration in the first line is equivalent to:
window.age = 2;
So the global object window
also has an age property, but since this
is the person
object we’re pointing to, we output the age
value of 1.
2. Function
When a function is not called with an object attribute (i.e. a normal function), this always points to a global object, which in the browser is “window”.
We extracted the doSomething
function and named it extractFn
, and then executed it again.
At this point extractFn
is no longer attached to the person
object, it has this pointing to the window object.
So how do we make sure that extractFn
is called correctly?
Your can use Function.prototype.call and Function.prototype.apply can dynamically change the function’s this.
The difference between call
and apply
is that call
needs to be passed one by one when there are multiple arguments, while apply
receives an array of arguments.
3. Constructor
When the function is called with the new operator, it returns an object with this pointing to itself.
As we all know, javascript is just a scripting language, there is no complete implementation of the class, but we can simulate the creation and use of the class through the prototype chain, the key point is the use of this
keyword.
4. with
Usually used as a shortcut to duplicate multiple attributes of an object, can be used without duplicating the object itself.
It looks great, but one fatal problem with with
is that when you accidentally assign a value to a property that doesn’t exist, it will leaks into the global scope!
Which is a strange side effect, so with is completely disabled in strict mode.
5. eval
This function accepts a string as an argument, and treats its contents as if the code already existed at that location in the program at the time it was written.
In strict mode eval
has its own lexical scopes, so if the above program runs in strict mode the output will be 2, and eval
will change its scopes at runtime, which can cause all sorts of serious problems if you let your users type in commands.
with and eval are very special and powerful, but I don’t recommend using them unless you have a specific need for them.
Thanks for reading, this is my first post on medium, I hope you’ll enjoy it.