Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant Javascript this in object method?

Noob question, searched but don't find an answer to this particular question. I'm constructing an object, and referencing the parameters of the argument using the 'this' keyword:

function Obj(a, b, c) {
  this.a = a;
  this.b = b;
  this.c = c;
  this.addMe = function() {
    alert(this.a + this.b + this.c);
  };
}

My question is a simple one: if a, b, and c exist solely within the object (in other words, there are no global variables declared using the same names), is the 'this' keyword required when using them within the addMe() method? Could the method not simply be written as:

this.addMe = function() {
  alert(a + b + c);
};

When I run this code by creating a new instance of Obj, it works exactly the same either way. And (not that I would do this) if I create global variables for a, b, and c different in value from the arguments I use when instantiating the new Obj, these have no bearing on the results from the method call. So, am I missing something that will come back to bite me if I don't use 'this' in the method?

like image 601
TKD Avatar asked Jul 13 '26 22:07

TKD


1 Answers

To demonstrate the difference/problem of using a + b + c

function Obj(a, b, c) {
  this.a = a;
  this.b = b;
  this.c = c;
  this.addMe = function() {
    console.log('addMe', this.a + this.b + this.c);
  };
  this.brokenAddMe = function() {
    console.log('brokenAddMe', a + b + c);
  };
}
var o = new Obj(1,2,3);
o.addMe(); // should be and is 6
o.brokenAddMe(); // should be and is 6
o.a = 4;
o.addMe(); // should be and is 9
o.brokenAddMe(); // should be 9 but still is 6
like image 183
Jaromanda X Avatar answered Jul 15 '26 10:07

Jaromanda X