Javascript this? Understand in simple language

The person sitting inside the house

Note: Understand the difference between method and function

Function vs Method

1. “this” inside Global Scope

2. “this” inside an Object

this inside Object

3. “this” inside a Function

Example 1: Here this loses its scope when js running in strict mode
this inside function can’t access it lose it scope

4. ‘Call’ function to access Object/this in a local function or method

Now openDoor function can access this
Pass some parameter when pass object with call

Now can I call local openDoor() with Object this.myHome and newHome?

  1. Yes Firstly remove all openDoor() declared inside the Objects.
  2. Use call() with function name and pass diffeent Objects
By this: We can use somebody else method to somebody else Object using call

5. ‘this’ inside an inner function

this will not work in inner function
  1. Use a variable: ex. that outside of innerFunction because outside of innerFunction this is available
Not a very good Approach
Better than first one but still not best
Arrow function will use this of openDoor() scope by default

6. this inside Constructor

Every time when creating new Home so define new objects like this.myHome, newHome..
Define createHome constructor for creating new Objects

7. this inside classes

Best way to create Object

--

--

--

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to write a react component (TypeScript) and publish to npmjs

GraphQL Tutorial: How to Build an App in PHP

Angular Reactive Forms: The Ultimate Guide to FormArray

CS373 Spring 2022: Kyle Kamka

[How-to] Run end-to-end Angular tests on continuous integration with Cypress

Pass your Angular certification exam today

P2P in Hyperledger Fabric

10 Projects Reactjs (NextJs Framework) + Tailwind

Using TypeScript Dynamic Imports in Angular

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shivam Gupta

Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

More from Medium

JavaScript Advanced Concepts

Here, There, or Everywhere: An Introduction to JavaScript Scope

For… in VS For…of — JavaScript

Introduction JavaScript