Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  77] [ 1]  / answers: 1 / hits: 15695  / 13 Years ago, mon, july 18, 2011, 12:00:00

Is there any way I can be less verbose in JavaScript by pointing a local variable by to an objects property?


For instance in PHP I can do this:


$obj->subobject->property = 'Foo';
$property =& $obj->subobject->property;
$property = 'Bar';
echo $obj->subobject->property;
// output 'Bar'

It's not a very good example but you get the idea.


I want to copy this behaviour in Javascript. I'm quite often having to go quite deep into objects and it's getting quite annoying having to do:


if (please.stop.making.me[somevar].type.so.much.length) {
please.stop.making.me[somevar].type.so.much[newSubObjectKey] = anObject;
}

// perform more operations on the object down here

It would be a lot easier to read and a lot easier to type:


var subObj = is.much.easier.to.type.once;
if (subObj.length) {
subObj[newSubObjectKey] = anObject;
}

// now that's much better

I know I should really know this already, but I'm just advancing to "advanced novice" in JavaScript.


More From » php

 Answers
12

In JavaScript, everything is passed by value, but the variable's type will determine whether it's a reference passed by value or not;



  • Objects are references

  • Primitives (numbers, strings etc) are passed by value.


In simple terms, if you pass a variable to a function that's an array, modifying it in the function will affect the parent.


However, passing it a value in the array will not. Naturally, there's absolutely nothing stopping you wrapping a primitive in an object to ensure it works like a "pointer".


[#91139] Friday, July 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cayden

Total Points: 314
Total Questions: 107
Total Answers: 101

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
;