[Javascript] Unexpected Result
liorean
liorean at gmail.com
Thu Aug 5 02:36:11 CDT 2010
> On Wed, Aug 4, 2010 at 2:51 AM, liorean <liorean at gmail.com> wrote:
>>>> If you want to do the equivalent of passing around
>>>> references, then you need to pass around a reference type from which
>>>> you read a property, and store new values in a property of that
>>>> object.
>> Reference type means object, array, function mostly. Things that
>> aren't value types/primitives.
>>
>> QQ = $.a.LASTLOSER; // => 5
>> QQ[2] = 2; // => 2
>> QQ[2]; // => 2
>> $.a.LASTLOSER[2] // => 2
On 4 August 2010 15:47, Mike Dougherty <mdougherty at pbp.com> wrote:
> So how do we get an object reference to a single element of an array?
> Is it possible?
>
> var myArray = ['a','b','c'];
> var refArray = myArray; /* this makes a reference to the object */
> var pos1 = myArray[1]; /* this makes a value assignment to an
> arbitrary variable */
> refArray[0] = "X"; /* assign "X" to element 0 of refArray, which is
> effectively an alias of myArray */
> pos1 = "Y"; /* assign "Y" to an arbitrary variable */
>
> alert( myArray.join(",") ); /* displays: X,b,c */
>
> Is it possible to get references to primitive array elements? If I
> really needed to do this, would I have to make each element an object
> so the array element references an object and a variable assigned the
> element would also get the object reference?
>
> var myObjArray = [ {"value":"a"},{"value":"b"},{"value":"c"} ];
> var pos1 = myObjArray[1];
> pos1.value = "X";
>
> alert( myObjArray.toJSONString() ); /* or some other way to display a
> complex object */
Making every value you want to do this with be contained in an object
will definitely work. Another way to do it is through using a closure
and a function call:
function enclose(obj,prop){
return function(val){
return arguments.length>0?
obj[prop] = val:
obj[prop];
};
}
QQ = enclose($.a.LASTLOSER,2); // => fn() -> 5
QQ(2) // => 2
QQ() // => 2
$.a.LASTLOSER[2] // => 2
I'm pretty sure you could use getters and setters or maybe toString,
valueOf bindings on objects to achieve the same or similar effects
without the function call syntax, too.
--
David "liorean" Andersson
More information about the Javascript
mailing list