0

I'm new to JavaScript. I've read that the context of this changes depending on how the function is being invoked (ie: from a variable, as a callback etc). I cannot find anything that says when I need to use this and when I don't. I've seen lots of code use this and seen code without it.

ie: Here is a for loop inside a function. It works. It doesn't use this

var output="";

for(var i=0; i<input.length; i++) {
    output = input.charAt(i) + output;
}
return output;
AfterWorkGuinness
  • 1,481
  • 1
  • 22
  • 42
  • Your question is a duplicate, and this post has a good answer: http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – BJ Safdie Jun 11 '15 at 01:36

1 Answers1

0

this is a pretty complicated concept in Javascript. There aren't strict rules about when you have to use this, but there are some situations where it's useful.

Mozilla Developer Network - this

In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called

Understand JavaScript’s “this” With Clarity, and Master It

One example where you almost always use this is when using an ES5 constructor. You apply properties to the constructor using this and then they are created as object properties on the instance created.

function Person(name) {
   this.name = name;
}

var me = new Person('yourname');
me.name // 'yourname'
Aweary
  • 2,195
  • 11
  • 25