First, See my code plz.
function test(){
this.item = 'string';
this.exec = function(){
something();
}
function something(){
console.log(this.item);
console.log('string');
}
}
And I made class and call 'exec function', like this code
var t = new test();
t.exec();
But result is...
undefined
string
I wanna access from something function to test.item.
Have you any solution?
You need to call something
with apply
so that this
is properly set inside of something
:
function test(){
this.item = 'string';
this.exec = function(){
something.apply(this);
}
function something(){
console.log(this.item);
console.log('string');
}
}
As @aaronfay pointed out, this happens because this
doesn't refer to the object that new test()
created. You can read more about it here, but the general rule is:
If a function is invoked on an object
, then this
refers to that object
. If a function is invoked on its own (as is the case in your code), then this
refers to the global object, which in the browser is window
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With