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;
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.