Reputation: 422
I have some code that isn't working and I don't understand why. I boiled it down to this simple example:
function Load() {
this.data = {
isLoaded: false,
};
this.load1 = function() {
console.log(this.data.isLoaded);
};
this.system = {
load2: function() {
console.log(this.data.isLoaded);
}
};
}
let a = new Load();
a.load1();
a.system.load2();
Why is this.data defined in the load1 function but undefined in the load2 function? Is there a way to get it working with the structure that I want (the second form)?
Thanks.
Upvotes: 0
Views: 583
Reputation: 1
It will work when you explicitly bind the context: a.system.load2.call(a);
Upvotes: 0
Reputation: 10204
This will work.
Put this.data
into function scope
variable called parentData
and you can use that value on any child.
this
in this.system.load2
refers this.system
content and it won't call parent data.
function Load() {
this.data = {
isLoaded: false,
};
var parentData = this.data;
this.load1 = function() {
console.log(this.data.isLoaded);
};
this.system = {
load2: function() {
console.log(parentData.isLoaded);
}
};
}
let a = new Load();
a.load1();
a.system.load2();
Upvotes: 1
Reputation: 3411
It's always a good idea to run console.log(this). It's all about what "this" refers to.
Upvotes: 2
Reputation: 99
I believe this has to do with scoping.
this.data.isLoaded
is referring to the current scope of load2
this.system = {
load2: function() {
console.log(this.data.isLoaded);
}
};
Upvotes: 0