According to the documentation:
Inside a Function (...) this
will default to the global Object.
That is, the code below (running in a browser) will print "true":
function f() {
// no browser, this é igual a window
console.log(this == window);
// no Node, this é igual ao objeto global
//console.log(this == globalThis);
}
f();
And in this case no matter where the function is called, the this
her remains the same:
function f() {
console.log('dentro de f =', this === window);
}
let obj = {
chama_f() {
console.log('dentro de obj.chama_f =', this === obj);
f();
}
};
obj.chama_f();
The output of this code is:
dentro de obj.chama_f = true
dentro de f = true
That is, within the function chama_f
, the this
is equal to obj
, but within the function f
, the this
remains the window
. Even though f
has been called within chama_f
, no matter, the this
is not affected by this
who called her.
That is what is happening in your case. Within the function consta
, the this
refers to obj2
, but within comparaComThis
, the this
is the window
.
let comparaComThis = function (param) {
console.log('comparaComThis =', this === window);
}
const obj2 = {
consta(){
console.log('consta =', this === obj2);
comparaComThis(obj2);
}
};
obj2.consta();
The exit code above is:
consta = true
comparaComThis = true
If you want to change the this
that comparaComThis
sees, an alternative is to use call
(which is explained in more detail here):
let comparaComThis = function (param) {
console.log('comparaComThis =', this === param);
}
const obj2 = {
consta(){
// aqui o "this" é obj2, e com call() eu informo que também será o "this" da função comparaComThis
console.log('consta =', this === obj2);
comparaComThis.call(this, obj2);
}
};
obj2.consta();
The first argument of call
is the object that will be seen as this
inside comparaComThis
. In case, I passed the this
concerning the function consta
, that we have seen in the previous example that is obj2
. And from the second argument on is what will be passed to the function comparaComThis
(in case I passed obj2
, that is, within the function, param
will be obj2
).
Yes, it’s confusing. But that’s how the this
it works, every hour it can be a different thing...
And not directly related, but in this case you could also declare the function as:
function comparaComThis(param) {
etc...
}
In this case there is no gain in using a Function Expression, but since it’s a simple example, it doesn’t matter either. But there are cases where it does, learn more reading here.
But in this particular case, in mine,?
– Arthur
@Arthur But I showed that the
this
moult. Withinconsta
, thethis
is equal toobj2
, and withincomparaComThis
, thethis
is the global object (window
run in a browser,globalThis
run on Node). I didn’t understand what you didn’t understand :-)– hkotsubo