Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

php - Javascript equivalent of assign by reference?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...