I am going to write about the "behind the scenes" that you are asking for. Unfortunately this might confuse you, instead of making things clearer as JavaScript is quite a "different" language on its own.
In JavaScript a function is an object. Sometimes even called a first-class object. It has everything an object has (attributes and methods) and in addition can further more be invoked. Don't believe me? See for yourself:
function abracadabra()
{
return "this is magic";
}
console.log(abracadabra.name);
console.log(abracadabra.call());
Now a method is simply another function to which an attribute of an object is referring to. Let's take your example:
let obj = {
name : "something",
print() {
console.log(this.name);
}
}
Here obj
is defined as an object with two attributes. A value type and a function. When you call the obj.print()
function the following happens:
- The function is called.
- The so-called function context
this
is set to the object that the method is called upon. You can use this
to access other attributes of the same object.
What exactly is this
? As said it is the so-called function context that can refer to four different objects depending on how a function is called.
- The function is called as a function. e.g.
abracadabra()
=> this
is referring to the global context, to which it is always referring by default.
The global context is dependent on the environment JavaScript is executed in. Remember JavaScript can not only run in a browser. It can also be used as a server-side scripting language. In the browser the global context is the current browser window. Don't believe me? See for yourself:
// We are not in any method, still "this" is available:
console.log(this.toString());
The function is called as a method. e.g. obj.print()
=> this
is referring to the object the method is invoked on. I described this above.
The function is called as a constructor. e.g. new abracadabra()
=> A new empty object is created and this
is referring to it. Now the function should extend the empty object with attributes.
The function is called using its apply
or call
methods => this
is referring to whatever you pass as the very first argument of these methods.
So to sum it up: It can get tricky to really understand how these things work in JavaScript. This is because basically there are only objects and functions in the language. Methods look like methods, but are in reality only functions as well.
To get a really good in depth understanding I can recommend the book Secrets of the JavaScript Ninja.