Why can’t the context be gleaned by the j/s?
This is not a question about can and cannot. The Javascript engine is designed to use certain concepts such as for example scope
and execution context
. It is difficult to give a full explanation of these concept in just a few lines. But here are the (very) broad lines.
Scope
Javascript uses lexical scope.
This is a concept defining which variables any given function
has access to. This is determined by how you write your code. It follows from this concept that any given function has access to variables placed by you:
- in the global scope;
- in any function containing the function in question.
This can be illustrated by the following example:
var one="one" //in the global scope
function A () { // access to one and two
var two = 'two'
function B () { // access to one, two and three
var three="three"}
function C () { // access to one, two, three and four
var four="four"
};
};
};
If you place a function
as a value
of an property
on an object
it becomes a method
. A method only has access to the global scope (disregarding functions nested inside a method) and variables inside itself:
var one="one"
var myObj = { // in the global scope
myFunctions: {
myFunction1: function() {}, // have access to one and myObj
myFunction2: function() {} // have access to one and myObj
}
};
That is why you in your example would have to reach m1
by calling o.m1()
;
Execution context
A function always has a this
value (disregarding arrow functions).
The value of this
is always properties inside an object. The determination of which object depends on the function’s execution context. The execution context more specifically depends on the function’s callsite as the value of this
will be set to:
- the object (level) containing the call of the function; or if not contained within another function
- the global object
This can be illustrated by an example:
var one="one"
var myObj = {
two: 'two',
three: 'three',
myFunction: function () { // this points to myFunction, two and three
function () { //this points to one and myObj
}
};
Now the above example is actually what can really lead you to think that now you understand this
and therefore you lower your guards and before you know of it this
is biting you in your a**. It is extremely important to remember the part about the function’s callsite:
var myObj = {
name: 'myObj',
myFunction: function() {console.log(this.name)
};
var anotherObj = {
name: 'anotherObj',
notAnotherFunction: myObj.myFunction
};
myObj.Myfunction(); // myObj
anotherObj.notAnotherFunction(); // anotherObj
In the above example the same function is called twice but with different callsite’s and consequently with different values of this
.
I can recommend you reading You don’t know JS series if you want to selfstudy to get to the bottom of amongst others the above concepts.
solved Use of ‘this’ in javascript object methods