[英]Javascript accessing inner function from outside
I have the following json object 我有以下
json对象
{
....
....
data: function() {
var x = 10;
function isBig() {
return x>6;
}
return x;
}
}
I want the isBig
to be a function inside data. 我希望
isBig
成为数据内部的函数。
When I call data.isBig
I am getting undefined
and data.isBig()
gives me an error saying isBig
is not a function. 当我调用
data.isBig
我变得undefined
而data.isBig()
给我一个错误,指出isBig
不是函数。
First of all, that is not JSON. 首先,这不是JSON。 It is an object.
它是一个对象。 The way your object is structured currently,
isBig
is only accessible from inside data
. 当前,您的对象的结构方式
isBig
只能从内部data
访问。 If you want to access it outside data
, the simplest way is to make it a property of the outer object: 如果要访问外部
data
,最简单的方法是使其成为外部对象的属性:
{
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. 调用
data()
正常工作(返回10),而调用new data()
返回具有属性isBig
的对象,该属性对应于该函数。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.