开发者

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

开发者 https://www.devze.com 2022-12-26 06:14 出处:网络
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 ha开发者_如何学编程ve to assign it the new len

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 ha开发者_如何学编程ve to assign it the new length again?


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. Hence, n is not aware of the object property it came from, it merely stores a number. Primitive types in JavaScript are assigned/passed by value, whereas objects are passed by reference. This is why doing 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.

Note: By "primitive type" I mean any of the following: Undefined, Null, Boolean, Number, or String


No, you will have to re evaluate the variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号