Reputation: 476
Just now I started using the this
keyword, and I have been wondering, why doesn't "this" work?
var obj = {
thas: this,
obj2: {
obj3: {
thos: this,
lol: "lol",
pap: function() {
console.log(obj.obj2.obj3.lol);
console.log(this.lol);
console.log(thos.lol);
}
}
}
};
obj.obj2.obj3.pap();
take a look at the third console.log()
.
I am defining the variable so why am I this error: Uncaught ReferenceError: thos is not defined
Upvotes: 1
Views: 81
Reputation: 14195
A function's
this
keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.In most cases, the value of
this
is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called, and ECMAScript 2015 introduced arrow functions whose this is lexically scoped (it is set to the this value of the enclosing execution context).
When a function is called as a method of an object, its this
is set to the object the method is called on. So, this.lol
works fine and equals to just calling lol
, since they're both in the scope.
But what happens when thos.lol
is called? Since this
is set an object property value, the virtual machine thinks this
is in global scope:
In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.
So, you call thos.lol
, it sees the global object and gives you undefined error. Try to obj.obj2.obj3.thos.lol;
in console and you'll see undefined. Try to obj.obj2.obj3.thos;
in console and you'll see the global object.
Upvotes: 3
Reputation: 446
I think thos
needs to referenced in the same way as lol
. You used this.lol
to access lol
, so to access thos
you have to access this.thos
, which probably wouldn't work as this.thos.lol
. OOP gets weird sometimes. If you want to use thos
instead, define it outside of the object and give that a try...
EDIT: Here's the modified code:
// this is the new line:
var thos = this;
var obj = {
thas: this,
obj2: {
obj3: {
lol: "lol",
pap: function() {
console.log(obj.obj2.obj3.lol);
console.log(this.lol);
console.log(thos.lol);
}
}
}
};
obj.obj2.obj3.pap();
Hope this helps!
Upvotes: 4
Reputation: 1204
this
refers to the parent object when referred to in an object's property. Inside of the pap()
method you can declare:
var thos = this;
Then you can do:
console.log(thos.lol);
Upvotes: 2
Reputation: 3051
you're trying to access thos
when it's not in scope. pap: function() { }
creates a new function scope that doesn't know anything about thos
, so you need to either pass it in or do console.log(obj.obj2.obj3.thos.lol);
instead of just console.log(thos.lol);
Upvotes: 0