总是转换成对象

时间:2012-04-22 09:04:42

标签: javascript json

我可以在Javascript中做一些自动转换的内容:

var x = 0;

进入以下(但仅在内存中 - 我不想更改“查看源”):

var x = {Value: 0};

例如:

var x = { Value: 0 };

function a(x)    //This function doesn't work if the parameter is not an object, and it would be better if I didn't have to write { Value: 0 }
{
    x.Value++;
}
a(x);
alert(x.Value);

2 个答案:

答案 0 :(得分:1)

这个问题缺乏背景和细节,但也许可以这样做:

function transform(x) {
     return { Value : x };
}

然后

x = transform(x);

答案 1 :(得分:0)

查看watchObject.watch() for all browsers?,例如:

var a = function (x) {
    x.value++;
};
var myVariables = {};
myVariables.watch("x", function (prop, oldval, newval) {
                     if (typeof newval !== 'object') {
                         return {"value": newval};
                     };
                 });
myVariables.x = 0;
a(myVariables.x);
alert(myVariables.x.value);