They are taken from jquery vid tutorials for premium.
http://tutsplus.com/lesson/the-this-keyword/ Jeff explains what 'this' means every time, but I'm not sure I understood all these considerations.
eg. one
function doSomething(e) { e.preventDefault(); console.log(this); } $('a').on('click', doSomething);
In this case, "this refers to the" element "(in this case, the parent)
I assume that because here the operator is:
$('a').on('click', function (e) { e.preventDefault(); console.log(this); }
So 'a' is the parent
eg. 2
var obj = { doIt: function(e){ e.preventDefault(); console.log(this); } } $('a').on('click', obj.doIt);
In this case, "does this still refer to the" element "(*, but apparently this is not the parent object?)
It seems that this time we are calling a method, but the statement is still the same as, for example, 1
* One thing in the textbook confuses me a little. I thought that 'this' always refers to the parent, so in this case, a is still the parent. But (at 05.23 in the textbook) he points out that this is not so, stating: “there may be times when you want 'this' to refer to its parent object, which would be" obj ", in which case it creates eg. 3.
eg. 3
var obj = { doIt: function(){ console.log(this); } } $('a').on('click', function(e){ obj.doIt(); }; e.preventDefault();
In this case, "this refers to the obj object"
I believe this is due to the fact that 'this' is in a nested function, since this operator is equal to:
$('a').on('click', function(){ function(){ console.log(this);} }; e.preventDefault();
I really don’t understand why, although, in particular, I read in the article that in this function 'this' "loses its path and refers to the main object (window object)".
Eg4
var obj = { doIt: function(){ console.log(this); } } $('a').on('click', function(e){ obj.doIt.call(this); e.preventDefault(); });
In this case, "This refers to" a "
According to the Javascript Definitive Guide, "The first argument to call () is the object on which the" Here "function should be called, this is used as the first argument. But "this" is not the object on which the function should be called?
I think I get that the call function is there to call the function and use its first parameter as a pointer to another object, but I don’t understand why using 'this' means that the function is called by 'a'. This is not what I saw in other calls ().
Sorry for such a mammoth. Hope someone else is reading this scene ...