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.
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()
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.