【问题标题】:JavaScript, inherited function is printed out as undefinedJavaScript,继承的函数被打印为未定义
【发布时间】:2013-11-10 20:21:21
【问题描述】:

我想知道为什么 JSON.stringify(this.Master.Func) 返回“未定义”而不是 function() { ... }

函数本身通过添加()来执行。

JSfiddle:http://jsfiddle.net/t4ngY/

代码

var $ = {}; // some global

var Master = 
    {
        property: 'Property',

        Func: function()
        {
            console.log('I am Func inside Master');
        },

        PassToGlobal: function()
        {
            $.master = this;
        }
    };

Master.PassToGlobal();

var Slave =
    {
        Master: $.master,

        ShowFunc: function()
        {
            console.log(JSON.stringify(this.Master.Func)); //returns undef
            this.Master.Func(); //prints `I am Func inside Master`
        }
    }

Slave.ShowFunc();

【问题讨论】:

标签: javascript json oop stringify


【解决方案1】:

如果您想查看函数文本,您可以像这样简单地调用toString 方法

console.log(this.Master.Func.toString()); 

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多