从JSON对象调用函数 [英] Calling functions from a JSON Object

查看:126
本文介绍了从JSON对象调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我定义以下json:

Hi,

I define the following json:

var testobj = {
    firstfunc: function(){
        return setInterval(this.testfunc, 1000);
    },
    testfunc: function(){
        console.log('test');
        this.otherfunc();
    },
    otherfunc: function(){
        console.log('otherfunc');
    }
}



如果我调用testobj.testfunc(),则控制台将显示"test"和"otherfunc".到目前为止还好.

如果我用intervall调用firstfunc,在内部调用"otherfunc",则控制台将输出:this.otherfunc不是函数.
但是this.otherfunc是一个函数,并且如果我在testfunc中调用它的话也可以使用.



if I call testobj.testfunc(), the console prints "test" and "otherfunc". Fine so far.

if I call firstfunc with a intervall, that calls "otherfunc" inside, the console prints: this.otherfunc is not a function.
But this.otherfunc is a function and works if I call it inside testfunc.

推荐答案

只要要包含函数成员,它就不是JSON: http://en.wikipedia.org/wiki/JSON [
As soon as you want to include function member, this is not JSON: http://en.wikipedia.org/wiki/JSON[^].

JSON is nothing but a subset of Javascript codes. The problem is unclear at all. How is that related to JSON at all? Please read the article above.

—SA


我认为问题在于函数的范围
您在json中使用setInterval函数时,它不具有otherfunc的范围.

您应该使用object来调用函数,在创建对象之后也是如此,否则它将再次产生错误.
I think the problem is with the a scope of the function
Your setInterval function does not have the scope of your otherfunc as you are using it inside your json.

you should use object to call the function, that too after creating the object otherwise it would give error again.


这篇关于从JSON对象调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆