JavaScript Object Methods, "this"

In JavaScript, objects are created for representing real-world entities, such as orders, users, and more. Here is an example:

let site = {
  name: "W3Docs",
};
console.log(site);

In the real world, you act like this: login, logout, choose something from a shopping cart, and more.

In JavaScript, you can represent actions by functions in properties.

Examples of Methods

Your first step while studying JavaScript object methods should be to learn how to “say welcome”. The example will look like this:

let site = {
  name: "W3Docs",
};
site.welcome = function () {
  console.log("Welcome to W3Docs!");
};
site.welcome(); // Welcome to W3Docs!
A Function Expression is used here for creating a particular function and assigning it to the site.welcome property of the object.

So, site can respond only after calling it.

A particular function that is the property of an object is known as a method. In the example given above, welcome is a method of the object site.

Moreover, a pre-declared function can be used as a method. To do that, you need to invoke the following command:

let site = {
  name: "W3Docs",
};
site.welcome = function () {
  console.log("Welcome to W3Docs!");
};
site.welcome(); // Welcome to W3Docs!

Description of Object-oriented Programming

Object-oriented programming (in short “OOP”) is targeted at writing codes by using objects to represent entities.

OOP can be described as a science of its own. A lot of research has been done to fully explore how to choose the right entities, how to organize the interconnection between them, and a lot more. That’s a whole new architecture.

Shorthand of Method

You can use a short syntax for methods in an object like this:

// method shorthand
let site = {
  welcome() { 
    console.log("Welcome to W3Docs");
  }
};
site.welcome();

In this example, you can see that the word “function” is omitted, and it’s just written welcome. Of course, there can be differences linked with object inheritance. Anyway, in most of the cases, it is more preferred to use a shorter syntax.

“this” in Object Methods

Generally, for doing its job, an object method must have the information kept in the object.

For example, the code that is inside site.welcome() might need the site.name.

A method can use “this” keyword for accessing the object.

The object “before dot” should be the value of “this”.

For instance, you can call the method as follows:

let site = {
  name: "W3Docs",
  welcome() {
    // "this" is the "current object"
    console.log(this.name);
  }
};
site.welcome(); // W3Docs

In the above-given example, while executing site.welcome(), site will be the value of “this”.

You have the option of accessing the object without using “this”. Just reference it via the outer variable like this:

let site = {
  name: "W3Docs",
  welcome() {
    console.log(site.name); // "site" instead of "this"
  }
};
site.welcome();

But, take into consideration that such kinds of codes can’t be reliable. In case of copying the site to a different variable (for example, anotherSite = site) overwriting site with another thing, you will be directed to a wrong object.

Here is an example:

let site = {
  name: "W3Docs",
  welcome() {
    console.log(site.name); // leads to an error
  }
};
let anotherSite = site;
site = null; // overwrite to make things obvious
anotherSite.welcome(); // Whoops! inside welcome(), the old name is used! error!

“this” can be Unbound

Commonly, the JavaScript keyword “this” can be used in any function on the contrary with other programming languages.

The following example doesn’t have any syntax errors:

function welcome() {
  console.log(this.name);
}

In the following example, the same function is accredited to 2 different objects, and it includes different distinctive “this” in the invocations:

let site = {
  name: "W3Docs"
};
let anotherSite = {
  name: "anotherSite"
};
function welcome() {
  console.log(this.name);
}
// use the same function in two objects
site.func = welcome;
anotherSite.func = welcome;
// these calls have different this
// "this" inside the function is the object "before the dot"
site.func(); // W3Docs (this == site)
anotherSite.func(); // anotherSite  (this == anotherSite)
anotherSite['func'](); // anotherSite (dot or square brackets access the method – doesn't matter)

So, simple steps are used here: If you first call obj.func(), then you need to run this is obj during the invocation of func. This means that in the above-given example, either site or anotherSite is used.

Invoking without an object: this == undefined

The function can even be called without an object as follows:

function welcome() {
  console.log(this);
}
welcome();

In the above-mentioned example, this is undefined in the strict mode. In the event of trying to enter this.name, an error can occur.

The value of “this” in a non-strict mode will be the global object.

Commonly, a call like this can cause a programming error. In case there is this in the function, it should be invoked in the object context.

Outcomes of Unbound “this”

If you are already used to another programming language, possibly you are familiar with the idea of “bound this” in which methods, characterized in an object always obtain “this” referencing the object.

“this” can be described as free in JavaScript. Hence its value doesn’t depend on where the method was confirmed. But it more depends on the “before dot” object.

The given concept of “this” has both advantages and disadvantages. On the one hand, you can use the function for a variety of objects. On the other side, the more flexibility, the more chances to make mistakes. Your aim should be to learn how to work with it to get benefits and avoid mistakes.

Arrow Functions Don’t Have “this”

Arrow functions are unique as they don’t have their own “this”. In case you start referencing it from a function like that, it will be taken from an outer “normal” function.

In the following example, arrow() uses this from the method: site.welcome().

let site = {
  name: "W3Docs",
  welcome() {
    let arrow = () => console.log(this.name);
    arrow();
  }
};
site.welcome(); // W3Docs

The special arrow function method is especially useful when you don’t wish to have a separate “this” but want to take it from a context beyond.




Do you find this helpful?

Related articles