-1

Can I do something in Javascript that will automaticaly transform this:

var x = 0;

into the following (but only in memory-- I don't want to change the "view source"):

var x = {Value: 0};

For exemple:

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);
Machavity
  • 30,841
  • 27
  • 92
  • 100
user1342369
  • 1,041
  • 2
  • 9
  • 9
  • 1
    Can you give us an example of how you would use that? – georg Apr 22 '12 at 09:11
  • "it would be better if i don't have to write" an object where an object is required?!? just use `typeof x` inside your function – Aprillion Apr 22 '12 at 09:21
  • no, i mean that the variable is still an object but the declaration of the object is automatic – user1342369 Apr 22 '12 at 09:23
  • What you're looking for is called "pass by reference" and doesn't exist in javascript - for a reason, because in most cases it's a bad idea. – georg Apr 22 '12 at 09:38
  • @thg435 uh.. objects are passed by reference in javascript – Aprillion Apr 22 '12 at 09:56
  • @deathApril: no they are not. Please read http://en.wikipedia.org/wiki/Evaluation_strategy carefully. – georg Apr 22 '12 at 10:01
  • @thg435 if you pass an object to a function and the function changes this parameter, the original object is changed - i don't care what do you want to call it.. – Aprillion Apr 22 '12 at 10:22
  • 1
    What, exactly, do you mean when you say you don't want to change the "view source"? Do you mean you don't want it to show up in the source at all? [Why](http://meta.stackexchange.com/q/66377/133817)? What's so important about not assigning an object to `x`? – outis Apr 22 '12 at 10:39

2 Answers2

1

The question lacks context and details, but maybe do it like this:

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

and then

x = transform(x);
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • and can I associate each declaration of a variable with this function ? – user1342369 Apr 22 '12 at 09:15
  • 2
    No, you cannot override variable declaration behavior in Javascript and you need to decorate variable declarations manually or perform the transformation in some other endpoint (e.g. have your own console.log()) – Mikko Ohtamaa Apr 22 '12 at 09:24
0

have a look at watch and Object.watch() for all browsers?, e.g.:

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);
Community
  • 1
  • 1
Aprillion
  • 21,510
  • 5
  • 55
  • 89