0

I want to pass a value to a Change function. But i want to pass only the reference inside the array. This works:

var test = ["Hello World","Hello You"];
HelloCar(test,0);

function HelloCar(myarray,key)
{
    myarray[key] = "Hello Car";
}

But this will fail:

var test = ["Hello World","Hello You"];
HelloCar(test[0]);

function HelloCar(myvalue)
{
    myvalue = "Hello Car";
}

Is there a way to pass only the real reference, without the complete data?

bergman
  • 185
  • 4
  • 13

2 Answers2

0

How about using a prototype:

Array.prototype.HelloCar= function ( idx ) {

  this[idx] = 'Hello Car'

 }

 test.helloCar(0)
Brian McGinity
  • 5,777
  • 5
  • 36
  • 46
0

Primitive types (such as Strings, Numbers and Booleans) are always passed as values, not references.

The closest you will get to emulating referencing variables is by wrapping them in an Object.

However, it might be comforting for you to know that you'll be able to achieve whatever you need to do without trying to bend JavaScript syntax to your will.

If you're anxious about a method having access to data it shouldn't (not that I can see any reason for this, in your instance), then I would write it like this:

var test = ["Hello World","Hello You"];

test[0] = HelloCar(test[0]);

function HelloCar(string){

  // any logic to change string in any way
  string = "HelloCar";

  return string;

}

This may seem a bit pointless, but let's pretend (for argument's sake) that you could pass a reference to a variable of a primitive type... If so, the only information the method would have access to would be it's value, because there is little more to a string variable than a memory address and a value. Being a string, it doesn't have a great deal of information, other than a bunch of characters. Ergo, any logic we need to apply to the variable in the way of contorting its value is actually going to be based on the same principals as the method above.

shennan
  • 10,798
  • 5
  • 44
  • 79
  • HelloCar is a value changer instance class. It should handle everything for itself. Of course i could use a change event, but the data holder needs to handle the real value switch. – bergman Jan 14 '14 at 16:21
  • I'm not quite sure if I understand what a `value changer instance class` is? – shennan Jan 14 '14 at 16:23
  • var change_car_tb = new Change_Textbox(change_car_value); Its basically a textbox – bergman Jan 14 '14 at 16:25