Object method And "this"

aryan sharmaaryan sharma
2 min read

namaste-welcome.gif (498×341)

Namaste!, this is Aryan Sharma's blog, and I hope you're all doing well & great.

Welcome to another blog of this JavaScript course.

📍You can find my blogs here↗️

Let's get started!

Objects

Basically objects are any real-entity or thing that can be touched, feel & have some properties. e.g. car, human, table.

let user = {
  name: "Aryan",
  age: 18
};

In real-world, an user has some properties, or some unique identity i.e. name and age.

User can perform any actions and these include clicking link for an interview, signing in bank for paying bills, in these clicking signing represents user's response on something.

In JavaScript, properties' functions represent actions.

Methods in OOP (Object Oriented Programming)

Methods are the functions that are used with objects.

Methods define the behavior of the objects and are called to perform certain actions on user's response.

Let's understand with an example:

user.greet = function() {
  alert("GM");
};

user.greet(); //GM

Here we’ve a Function Expression to create a function.

Here we have greet method for user

Other form of method...

user = {
  greet() { 
    alert("GM");
  }
};

This looks better!

Use of "this" in methods

It is usual to object method as it accesses information present in the object.

For instance, the code inside user.greet() may need the name of the user.

This keyword can be used by a method to access the object.

Understand with the help of an example:-

let user = {
  name: "Aryan",
  age: 18

  greet() { 
    alert(this.name);
    alert(this.age);
  }

};

user.greet(); // Aryan //18

While executing, when it reaches user.greet value of this will be user.

Also, we can get our output by using . notation by accessing value with the help of key in a object - user.name

but there's a problem when we copy it's value to another variable.

No Access to Arrow functions

Arrow functions are unique in that they don't "own" this. This is taken from the outer "normal" function if we reference it from one of these functions.

Here, for example, arrow() makes use of this from the external user.sayHi() technique:

Example:

let user = {
  Name: "Aryan",
  greet() {
    let arrowsgn = () => alert(this.Name);
    arrow();
  }
};

user.greet(); // Aryan

See u in the next blog...Stay tuned🎶

Don't forget to follow me on:
Twitter And LinkedIn

6
Subscribe to my newsletter

Read articles from aryan sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

aryan sharma
aryan sharma

Hey, Awesome ones! Aryan this side👋 Full-Stack Developer, Life-Long Learner, Optimistic Using this blog to help code newbies. Learn with me! :)