显示一个对象属性值,而另一个引用对象为空

编程入门 行业动态 更新时间:2024-10-27 09:33:26
本文介绍了显示一个对象属性值,而另一个引用对象为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 var obj={name: "faizan"} var obj2= obj;//obj2 pointing to the same memoray location of obj console.log("before making null obj",obj2.name); obj={}; //obj became null console.log("after making null obj",obj2.name);//now this will need to be null but is working why??

我创建了对象(obj),然后将它分配给第二个对象(obj2),最后使 obj null但在那之后 obj2.name 显示我faizan".为什么?现在不需要显示任何内容,因为 obj null

i made object (obj) then assigned it to the second object (obj2) and finally make obj null but after that obj2.name showing me "faizan". why? it need to show nothing cause obj null now

推荐答案

您认为它的工作方式是错误的.第二次设置 obj = {}; 时,您并没有取消原始对象.您正在创建一个全新的空对象,而 obj2 仍然引用原始对象.

The way you believe it to work is incorrect. The second time you set obj = {}; you aren't nullifying the original object. You are instead creating an entirely new empty object, while obj2 still references the original.

您可以通过使用父容器实现您的想法:

You could achieve what you think by using a parent container:

var obj = { container: { name: 'faizan' } }; var obj2 = obj; obj.container = {};

更多推荐

显示一个对象属性值,而另一个引用对象为空

本文发布于:2023-11-22 09:54:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616964.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   为空   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!