Reputation: 644
Let's say I have the following script:
var A = function() {
this.b = "asdf";
this.c = function() {
this.source = "asd";
this.data = function() {
var response;
$.getJSON(this.source, function(data) {
response = data;
});
return response;
};
};
};
The reason I made those closures is that I have other objects and variables inside A
, making an object-oriented app. I have some doubts regarding that script:
A.b
from inside the A.c
method? this
refers to the A.c
instance, not to A
anymore.Note: the purpose is to, on new A()
, generate an object like this:
{
b: "asdf",
c: {
source: "qwerty",
data: {
jsondata1: "jsonvalue1",
jsondata2: 3,
// ...
}
}
}
but I know instance.c
will still be a constructor function, and I have no clue how to make it an object inside another.
Upvotes: 0
Views: 53
Reputation: 7328
This should work
var A = function() {
var me = this; //<-- to let you refer to b inside the c function
me.b = "asdf";
me.c = new function() { // <-- added new here
this.source = me.b + 'abc';
this.data = function() {
var response;
$.getJSON(this.source, function(data) {
response = data;
});
return response;
};
};
};
a = new A();
a.b
returns "asdf" and a.c.source
returns "asdfabc". a.c.data
would still be the function though.
Upvotes: 1