简体   繁体   English

将DOM元素中的成员分配给变量是否会使变量自身更新?

[英]Would assigning a member from a DOM element to a variable enable the variable to update itself?

For example if I assign 例如,如果我分配

var n = document.getElementById('A').childNodes.length;

And then later append a child to A, would n update itself or would I have to assign it the new length again? 然后在A后面附加一个孩子,是否会自我更新,还是我必须再次为其指定新的长度?

No, it will not automatically update itself. 不,它不会自动更新。 The reason is that what you are doing is assigning the value of the length property, which is a number, to the variable n . 原因是您正在做的是将length属性的 (即数字)分配给变量n Hence, n is not aware of the object property it came from, it merely stores a number. 因此, n不知道它来自的对象属性,它仅存储一个数字。 Primitive types in JavaScript are assigned/passed by value, whereas objects are passed by reference. JavaScript中的原始类型是按值分配/传递的,而对象是按引用传递的。 This is why doing var o = document.getElementById('A'); 这就是为什么做var o = document.getElementById('A'); would work in the manner you describe - what you're assigning to o is an object and not a primitive type. 将按照您描述的方式工作-您分配给o是对象而不是原始类型。

Note: By "primitive type" I mean any of the following: Undefined, Null, Boolean, Number, or String 注意:“原始类型”是指以下任何一种:未定义,空,布尔值,数字或字符串

不,您将不得不重新评估变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM