DEV Community

Adewumi Emmanuel Femi
Adewumi Emmanuel Femi

Posted on

Demystifying 'This' in Javascript

The first question a beginner in programming would ask is, "what is 'this'? Well, I don't mean the kind you have in mind. In this context I'm talking about the 'this' that accompanies every block of code or function. So where does 'this' come from?

Every code block always has a context called 'this'. Most beginners always wondered where the this comes from (I was most beginners, most beginners was me).

When a code block is created, in this example, we will be using a function. All functions are prototype of the Object class, i.e. they inherit from the Object class. First we have to look at function from the angle of being an object. Let's take a look at what happens when you create a function.

function getAllUser(){
   let this = {} //(1)
}
Enter fullscreen mode Exit fullscreen mode

When a function is declared we have an Object initialized or created called 'this' as seen in (1) above. All methods and variables are created inside the 'this' object.

function createUser(firstName, lastName){
    let firstName = firstName;
    let lastName = lastName;
}
createUser.prototype = {
      fullName: function(){
          Alert(`Full name is ${this.firstName} ${this.lastName})
      }
}
function createUser(firstName, lastName){
    let this = {
      firstName: firstName,
      lastName : lastName
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The object class is parent to many other classes and it forms the basis of many classes we use often. The concept of 'this' is understandable because function itself is a prototype of Object class.

Top comments (2)

Collapse
 
pitypec profile image
Adewumi Emmanuel Femi • Edited

Thanks for your pointers, my bad. Fixed

Collapse
 
pitypec profile image
Adewumi Emmanuel Femi • Edited

The purpose of using function as oppose to using class in this example is to buttress a point which is that classes are prototype of function and most of what you could do with classes you could do with a function.