What is this?
In our natural language, we use this to refer to current Environment Objects:
If a person sitting inside the house says: this address so it means the address in which a person is currently present.
So we are inside the house so you can refer to the house like this.
Note: Understand the difference between method and function
1. “this” inside Global Scope
By default this point to the window object of browser
2. “this” inside an Object
If you are inside an Object so this will refer to the Current Object
@openDoor is a method of Object: this.myHome, newHome
3. “this” inside a Function
We should not use this direct inside a function (but we can use this in method- the function inside an Object)
4. ‘Call’ function to access Object/this in a local function or method
Using call function we can pass the reference / Object
It means execute openDoor function as a method of this
Pass some parameter with call : openDoor.call(this, “Shivam Gupta”);’
Now can I call local openDoor() with Object this.myHome and newHome?
- Yes Firstly remove all openDoor() declared inside the Objects.
- Use call() with function name and pass diffeent Objects
5. ‘this’ inside an inner function
Again i will say: Inside a function using this is not useful untill use: call, bind, apply
There is 3 solution for above problem
- Use a variable: ex. that outside of innerFunction because outside of innerFunction this is available
2. When call innerFunction so use call/bind to bind current this for innerFunction:
We can also use bind: bind basically creates a new function with current this
.bind() return a function so we call again lets break:
3. Best way: use Es6 arrow function
Arrow functions are a special type of function. It takes this from outer scope to inside function scope
6. this inside Constructor
In this example we are creating Object multiple times see:
So instead of creating Object like this, we will create constructor so no need to create Objects every time like this
Constructor is just function
We can concise our code like every time i need to use call methos so we can put openDoor function in prototype of constructor function: createHome
We use openDoor() inside prototype because of it automatically us this of its parent Function (createHome) so we don't need to pass externally this by — call/bind.
7. this inside classes
Use ES6 Classes instead of the constructor function for creating Objects and prototype methods in a cleaner way see:
If like this post please give a clap . Write in the comment section for any Question or suggestion. Thanks!