darkhorse
darkhorse

Reputation: 8782

Are there any downsides to using the object name directly (and not the this keyword) in JavaScript?

Let's say I have the following code:

var myObj = {
    // Case 1
    myFunc1: function() {...},
   
    // Case 2
    myFunc2: function() {
        console.log(this.myFunc1);

        console.log(myObj.myFunc1);
    }
}

In both cases, the result is the same. Now my question is this: are there any downsides to using myObj.myFunc1() always? I don't like using the this keyword, and there are often unexpected issues which I can't wrap my head around. If I just use my object's name to directly call the function, what sort of unexpected edge cases can I face?

Upvotes: 0

Views: 50

Answers (2)

Tore
Tore

Reputation: 1264

This really gets down to OOP and instance vs static methods.

For static methods, the result should be the same. For instance methods, function results may differ based on which instance of the object you have and the state of those objects.

You might want to read through this, it can explain in much more detail than I can add here:

https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

Upvotes: 3

Noa
Noa

Reputation: 1216

Both this and without this ways are avialable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:

class Profile {
  static Admin() {
    return "Admin";
  }
  usernameA() {
    console.log(Prfile.Admin());
  }
  usernameB() {
    console.log(this.constructor.Admin());
  }
}
class SubProfile extends Profile {
  static Admin() {
    return "SubProfile";
  }
}
new SubProfile ().usernameA(); // Profile
new SubProfile ().usernameB(); // SubProfile

Dependent to static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property should have the inherited value but could also be overridden.

If you expect static properties not to be overridden, use the explicit reference.

Upvotes: 1

Related Questions