【问题标题】:What is reference and How to know reference of the object in javascript什么是引用以及如何知道 javascript 中对象的引用
【发布时间】:2017-11-29 05:04:50
【问题描述】:

什么是对象中的引用以及如何在 javascript 中查看分配给对象的引用。我在对象中使用了 lodash _.clone(),并在下面做了一个示例

var  Obj = {id : 0, box: 0, ei : 0};
        var model = {id : 0,ob : [{c: 1, a: 0}],com: _.clone(Obj)};
        var old=_.clone(model)
        old.id=1;
        console.log(old.id===model.id); //false correct
        old.com.id=1;
        console.log(old.com.id===model.com.id);//true

更新 old.id 为 1 时,model id 没有更新,但是现在更新 old.com.id 为 1 时,model.com.id 也更新了,为什么?

【问题讨论】:

  • 什么是对象中的引用,对象是使用引用分配的。因此,当您执行var a = {} 时,a 将保存内存位置而不是{}如何查看分配给对象的引用 据我所知,你不能。 model.com.id 为什么也更新了? 因为,_.clone 不做深拷贝。它只复制第一级
  • 你可以参考这里的深拷贝选项:stackoverflow.com/questions/122102/…

标签: javascript json object web lodash


【解决方案1】:

_.clone 进行浅拷贝。这意味着它创建了一个新对象,然后对于旧对象中的每个值,它将相同的值分配给新对象。对于原语(布尔值、数字、字符串),这意味着它被复制了。这是必要的,因此许多不同的引用都可以具有“1”的值,但是当其中一个更新时,它们并不会全部更新。如果它是引用(对象和数组),则分配的值和原始值现在引用相同的东西。每当您分配某些内容时,这些规则都是正确的。

例如:

var a = {value:1} 
var b = {value:2} 
a.b = b // this sets the property "b" in a to the reference of the 'b' object. 
// so a.b and b now reference the same object
// so "a.b.value" is the *same* location in memory as "b.value"
// so if you update a.b.value or b.value you'll see it change in both references (because they are the same)

这个“记忆中的同一点”是关键。继续示例:

var c = _.clone(a) 

// these three lines are equivalent to the line above
var c = {}
c.value = a.value
c.b = a.b

// "c.b.value" is the "same spot in memory" as "a.b.value" and "b.value"
// So when you set it to a new value that value will change for all objects
// but "a.value" was just copied to c when it was created 
// So "c.value" and "a.value" are different spots in memory
// So changing "c.value" has no effect on "a.value"

对不起,如果 cmets 有点难以阅读,但我认为一次看一行而不是一连串句子会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2012-08-15
    • 2016-05-31
    • 2012-06-01
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多