显示一个对象属性值,而另一个引用对象为空 [英] A object property value is showing while the other refrence object is null

查看:57
本文介绍了显示一个对象属性值,而另一个引用对象为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 = {};

这篇关于显示一个对象属性值,而另一个引用对象为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆