Object.Freeze Javascript

This question already has an answer here:

  • What is the most efficient way to deep clone an object in JavaScript? 57 answers
  • How do I correctly clone a JavaScript object? 54 answers

  • I believe you're misunderstanding the concept of references in javascript. Objects are referenced in javascript, so when you do

    const b = a;
    

    basically you are assigning b a value of the reference a , in order to get your code to work, and actually "replicate" like you intend, you need to clone the object not pass a reference.

    You can use Object.assign({}, ...) to clone an object into a new one. (notice that its not deep cloning but it should get you going)

    let a = { "teste" : [1,2,3] }
    
    // I want 'b' freezed
    const b = Object.assign({}, a);
    Object.freeze(b);
    
    a.teste = [4,5,6]
    
    console.log(a)

    Objects in Javascript are passed by reference, so in your example, the variables a and b refer to the same object. Object.freeze works on the object itself, not the reference, so there's no difference whether you refer to it using a or b . This is the same as if you'd just set a property:

    let a = { "test" : [1,2,3] }
    const b = a;
    b.test = [4,5,6]
    console.log(a)
    

    If you want to freeze or modify b without affecting a , you'll need to clone it first. One way of doing this is using Object.assign :

    let a = { "test" : [1,2,3] }
    
    const b = Object.assign({}, a);
    Object.freeze(b);
    a.test = [4,5,6]
    
    console.log(a)
    

    This works by copying all of a 's properties to an empty object, then assigning that to b .

    链接地址: http://www.djcxy.com/p/24776.html

    上一篇: 我怎样才能在JavaScript中制作一个对象的副本?

    下一篇: Object.Freeze Javascript