问题描述
有没有什么方法可以通过将局部变量指向对象属性来减少Javascript中的冗长?
Is there any way I can be less verbose in Javascript by pointing a local variable by to an objects property?
例如在PHP中我可以这样做:
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.
我想在Javascript中复制此行为。我经常不得不深入到物体中,这让我很烦恼:
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
我知道我应该知道这一点,但我只是在Javascript中推进高级新手。
I know I should really know this already, but I'm just advancing to "advanced novice" in Javascript.
推荐答案
在Javascript中,一切是按值传递的,但变量的类型将决定它是否是通过值传递的引用;
In Javascript, everything is passed by value, but the variable's type will determine whether it's a reference passed by value or not;
- 对象是引用
- 原语(数字,字符串等)按值传递。
简单来说,如果将变量传递给一个数组的函数,在函数中修改它将影响父类。
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".
这篇关于Javascript相当于通过引用分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!