Reputation: 1857
I have the following json object
{
....
....
data: function() {
var x = 10;
function isBig() {
return x>6;
}
return x;
}
}
I want the isBig
to be a function inside data.
When I call data.isBig
I am getting undefined
and data.isBig()
gives me an error saying isBig
is not a function.
Upvotes: 0
Views: 74
Reputation: 816
obj = {
data: function(){
var x = 10;
return this.isBig(x);
},
isBig: function(x){
return x > 6;
}
};
And if you want to reproduce the function but useally your better off with an contructor add that point.
f = {
isSmall: function(){},
isBig: function(x){
return x > 6;
}
};
obj = {
data: function(){
var x = 10;
return this.isBig(x);
},
isBig: f.isBig
};
obj.data();
obj.isBig(2);
f.isBig(2);
Upvotes: 0
Reputation: 8921
First of all, that is not JSON. It is an object.
The way your object is structured currently, isBig
is only accessible from inside data
. If you want to access it outside data
, the simplest way is to make it a property of the outer object:
{
data: function()
{
var x = 10;
return x;
}
isBig: function(x)
{
return x > 6;
}
}
If you don't want to do that, then an alternative would be this:
{
data: function()
{
var x = 10;
this.isBig = function(x)
{
return x > 6;
}
return x;
}
}
Calling data()
works normally (returns 10), whereas calling new data()
returns an object with a property isBig
which corresponds to the function. This allows you to do this:
new myObj.data().isBig()
Upvotes: 3