Functions run in global scope ie. this points to global scope. Methods are functions in an object's directory and we invoke them using object reference ie. this points to the object on which the function is invoked.
It's important to understand that methods are still functions and can be invoked without object reference.
var x = 0;
var obj = {
a : function() {
console.log('hello ' + this.x);
},
x : 1
};
obj.a(); // prints hello 1, uses x defined in global context
b = obj.a;
b(); // prints hello 0, uses x defined in scope of objectvar x = 0;
var obj = { x : 1 };
function foo() {
console.log(this.x);
}
foo(); // prints 0
foo.call(obj); // prints 1call and apply let you execute a function in a specific context ie. they let you explicitly specify the value of this.
Every function in JavaScript - being an object - has its own methods, call and apply in addition to toString etc.
Yehuda Katz - Understanding JavaScript Function Invocation and “this”
Call - MDN
Apply - MDN
Ode to Code
JavaScript Refresher