This in JS
This! This is a very confusing keyword in programming world,
especially for new programmers. If you search for the definition you will find ‘current
execution context’. And this is all you need to know.😊
Just kidding😂😂
.When calling it inside a function it reference that
object calling the function (ps :you can’t use this inside arrow function) or
the global environment (browser, node.js …) for example:
Trying to run: console.log (this) in your browser will
give you data about the window you are using.
Let’s run it on node: we get :{} at least this is what
I get, it’s related to my node environment.😅
Ok know let’s try it inside a function:
But we call the function as a member of an object
function myFunction(){
console.log(this)
}
const obj={
name:"john",
myFunction
}
obj.myFunction()
And the result is:
{name: 'john',
myFunction: Æ’}
It’s a reference to the current object.
Using the new keyword will tell the program to create
object where ‘this’ is the new object. You sure noticed it when creating
proprieties and initializing it.
function Obj(param){
this.name=param;
this.greet=function(){
console.log('my name is: '+this.name)
};
}
const myObj = new Obj('o1')
myObj.greet()
noiiice 😂.so the ‘this’ is our new object and we
are building it. It’s a bit confusing i know.😓
In strict mode (‘use strict’) when referring to this
inside a function it will return undefined instead of the window.
+bind:
function displayName(){
return this.name;
}
const person={
name:"john"
}
const displayPersonName= displayName.bind(person);
console.log(displayPersonName())
And the result is: john!
The bind method tells will create a function (‘displayPersonName’)
it will take the logic of the function (‘displayName’) but it will use the ‘this’
of the object ‘person’. So each time we call this inside the first or second
function is like we are calling it inside ‘person’. I hope this makes sense.
+call:
Instead of creating a new function we will call ‘displayName’
and we will have the same result as the previous one:
console.log(displayName.call(person))
+apply:
It will do the same as call but it will take an array
as a second parameter. It’s an array of argument
Hope you enjoyed please give me feedbacks.
No comments