[Solved] Javascript: When and when not to use “this”


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.

2

solved Javascript: When and when not to use “this”