奇怪的JavaScript行为,调用转换器函数之前的变量值

时间:2011-09-13 13:11:40

标签: javascript jquery variables

我从Smarty传递了一些JSON数据。我将其应用于JavaScript变量options

如果你已经看过我之前关于日期格式的问题,你就会知道我需要对进来的数据做一些工作,所以我有一个名为chart_convert_dates()的函数被调用,传入选项(好吧,options.data),并在它返回后重新设置它。

如果您仔细阅读我的代码,您会注意到我正在调试options变量,并且在调用该函数之前它会从原来的更改!?

如果我注释掉函数调用,那么变量是不变的,因为它应该在那一点上。

这种情况发生在Chrome,FF ......发生了什么事?

{literal}

    <script type="text/javascript">

        $(document).ready(function() {

            // set JS var, this data is coming in from smarty
            var options = {/literal}{$options}{literal};

            // these should both be exactly the same
            debug.debug({/literal}{$options}{literal});
            debug.debug(options);

            // but the above outputs aren't the same! options has been modified
            // by the function below... that hasn't even fired yet!? We can prove
            // this by commenting out the following function call

            options.data = chart_convert_dates(options.data);

            // ... do something else

        });

    </script>

{/literal}

1 个答案:

答案 0 :(得分:2)

这当然是不可能的。

您可能会发现debug.debug()函数正在保存对其提供的对象的引用,而不是立即将其转换为字符串。然后,当您稍后查看其参数的内容时,输出将反映对象的当前状态,而不是 中的状态。

最好用以下示例解释:

var debug = {
    report: function () {
        // console.log(this._value);
    },
    debug: function (arg) {
        this._value = arg; // save a reference
    }
}

var options = {
    foo: 1
};

debug.debug(options);

options.foo = 2;

debug.report(); // will show 2 (http://jsfiddle.net/zQFPm/)

http://jsfiddle.net/zQFPm/