-2

Im curious when it is needed/best practice to use the keyword this. I understand that this is used when determining a functions this value but is it always needed?

The reason I am asking is because I have a internal function and it is called within my module and all it really does is sort some data you pass it. My question is should I call this function using the this keyword or stand alone.

E.g:

function formatSomeData(data){
  //code........
}

this.formatSomeData(data);

        OR

formatSomeData(data);

I get that the context of where the function is being called and what its purpose is matters in answering the question, but in this case like I mentioned, I really don't need to access the this object at any point. Is it still good practice to use it when calling functions? What I'm asking is not so much as to how "this" works, but when is it appropriate to use it and when isn't it.

Phil Dimeski
  • 21
  • 1
  • 6
  • If its a `method` of some kind, that means that the function is somehow directly related to an object, then its a good design decision to use `this`. Otherwise not – Jonas Wilms Feb 14 '18 at 06:30
  • 3
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Vasyl Moskalov Feb 14 '18 at 06:30
  • By the way `this.formatSomeData(data);` wont work in your case so the answer is obvious – Jonas Wilms Feb 14 '18 at 06:31
  • @JonasW. it might. In non-strict mode, `this` will point to `window` and any declaration not in a function will be a part of global scope. – Rajesh Feb 14 '18 at 06:33
  • @rajesh "in non-strict mode" ... talking about bad practices here... – Jonas Wilms Feb 14 '18 at 06:40
  • use 'this' keyword, when you are referring to the same object or want to call a method on the current object. If you have standalone method in an object, if you are invoking it from the same object, you can call using 'this' or even directly. 'this' is mainly used for readability i.e. we are invoking a method from the same object – Jayanth Feb 14 '18 at 06:41
  • @JonasW. practices comes in play when you have some knowledge about language. For a beginner, its difficult for to decide if they are on right/wrong path. Especially with JS where you can do same thing in 10 different ways. So even if its bad, its possible and many will use it – Rajesh Feb 14 '18 at 06:49
  • @JonasW. Have credited you in answer and have tried to give some explanation as to why it is a bad approach. If there are more, feel free to edit it. – Rajesh Feb 14 '18 at 07:02

4 Answers4

4

when it is needed/best practice to use the keyword this

This is usually used when you want to access something in some. So for instance, if you have a custom object and want to use some property inside some method, you should use this.

function Person(fname, lname){
  this.fname = fname;
  this.lname = lname;
  this.fullName = function(){
    return this.fname + ' ' + this.lname;
  }
}

var p = new Person('foo', 'bar');
console.log(p.fullName())

If you see, in current constructor, I created a function(fullName) which needs to access fname and lname properties of the object it is part of. This is a place this must be used.


Now while declaration, when to use this?

Any property in a constructor that is a part of this will be a part of the object. So if you need something that is only accessible to you but not outside, you can use function instead of this.

function Person(fname, lname){
  var self = this;
  self.fname = fname;
  self.lname = lname;
  
  // This function is private
  function getFullName() {
    var name = '';
    var seperator = '';
    if (fname) {
      name += self.fname;
      seperator = ' ';
    }
    if (lname) {
      name += seperator + self.lname;
    }
    return name;
  }
  this.fullName = function(){
    return getFullName();
  }
}

var p = new Person('foo', 'bar');
console.log(p.fullName())

As for your code, I have already explained in comment why it works:

In non-strict mode, this will point to window and any declaration not in a function will be a part of global scope.

But as rightly pointer by @Jonas W its a bad practice. Why it is bad?

  • Any variable defined without declaration statement(var|let|const) will become part of global scope.
  • Any variable with declaration statement outside any functions will become part of global scope.
Rajesh
  • 21,405
  • 5
  • 35
  • 66
0

For a starting JS developer it might be easiest to get concept of This by using it in an event listener callback. I. e., "click" event binds This to object which is the target (Like "look, i clicked on THIS!").

<ul class="dynamic-list" id="myList">
  <li class="dynamic-list__item">Item 1</li>
  <li class="dynamic-list__item">Item 2</li>
  <li class="dynamic-list__item">Item 3</li>
</ul>

<script type="text/javascript">
  let listItems = document.getElementById("myList").childNodes;
  [...listItems].forEach(function(item) {
    item.addEventListener("click", removeListItem, false);
  })

  // Callback for event, using THIS
  function removeListItem() {
    // Log the text content of <li> to the console. Which one? THIS one.
    console.log(this.textContent);

    // Get the parent of what? Of THIS! And remove its child. Which one? THIS one!          
    this.parentNode.removeChild(this);
  }

</script>

Of course Rajeshs answer is much, much more complex, but I hope THIS can be also helpful…

HynekS
  • 1,199
  • 1
  • 11
  • 22
0

Programming is a way to express things so that computers and humans can understand them.

Is it still good practice to use it when calling functions?

There is no exact answer. Both of your snippets do work. So the computer is able to understand it. However the second one is maybe confusing for humans (aka your coworkers):

 this.someFunc();

What should this refer to? Yes technically it refers to window, but from a human point of view it is unclear. Thats why i would definetly not refer to this in this case. However there are other good usecases for it:

 function changeColor(){
   //When just looking here it makes no sense to refer to this
   this.color = "green";
}

const car = { color: "grey" };

 //But now it makes sense as `this` refers to the `car` it is called on
car.changeColor = changeColor;

TLDR: Use this to refer to methods/properties, and leave it away when refering to pure functions and variables.

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
-1

'This' is used inside a function and it contains the value of the object that invokes the function.

For example:

function a(){
 this.newVariable = 'Phil';
}
a();
console.log(newVariable); //This line would display Phil

In this case, even though we just define newVariable inside the function a(). The object that invokes the function is the global object window, so 'this' points to window and this.newVariable is at the global scope.

Another example would be:

var c={
  log:function(){
    this.name = 'Phil';
   }    
}

In this case, 'this' points to the object c, since the log function will be invoked by c.

We have more tricky cases in the use of the object 'this' in Javascript. This is a good article to grasp the concept: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

Caio Gomes
  • 348
  • 5
  • 14