In trying to understand the 'this' keyword in JavaScript, I've looked at many resources, including the answers on this popular Stack Overflow question: How does the "this" keyword work?
I don't know if I am misunderstanding something, but everything I've read seems to be incomplete and missing a rule: Even though functions are objects, 'this' is treated differently for function-objects vs. other objects.
Consider the following code:
var object = {};
object.name = "object";
object.logMyName = function() {
console.log(this.name);
};
object.logMyName();
Because a function ('logMyName') is called on an object ('object'), 'this' is set to the object ('object') upon which the function ('logMyName') was called.
Now consider the following code:
var funcObject = function() {};
funcObject.name = "funcObject";
funcObject.logMyName = function() {
console.log(this.name);
};
funcObject.logMyName();
Although a function ('logMyName') was called on an object ('funcObject'), 'this' is not set to the object ('funcObject') upon which the function ('logMyName') was called.
Why does this discrepancy between types of objects exist, and why is it rarely/never discussed?