const Inner = function(Text) { this._Text = Text; this.Alert = () => { alert(this._Text["Message"]); } }; const Outer = function() { this.Text = { Message: "Hi" }; this.Inner = new Inner(this.Text); this.Alert = this.Inner.Alert; }; const OuterObject = new Outer(); OuterObject.Alert(); OuterObject.Text["Message"] = "Hello"; OuterObject.Alert();Salida: Hola->Hola
const Inner = function(Text) { this._Text = Text; this.Alert = () => { alert(this._Text["Message"]); } }; const Outer = function() { this.Text = { Message: "Hi" }; this.Inner = new Inner(this.Text); this.Alert = this.Inner.Alert; }; const OuterObject = new Outer(); OuterObject.Alert(); OuterObject.Text = { Message: "Hello" }; OuterObject.Alert();Salida: Hola->Hola
Estaba experimentando con copia superficial y copia profunda en Javascript. Luego ejecuté los códigos anteriores. No entiendo por qué la primera era una copia superficial y la segunda una copia profunda. Por favor, ayúdame.
Después de llamar a new Outer(); en su primer bloque de código, termina con this.Text dentro de Outer y this._Text within Inner apuntando al mismo objeto en la memoria, que es el objeto que creó en Outer :
{ Message: "Hi" } Esto se debe al hecho de que cuando pasas this.Text a Inner terminas pasando la referencia del objeto anterior. Como resultado, this._Text hace referencia al mismo objeto a this.Text hace referencia a. Esto significa que cuando modifica el objeto Text , el cambio también se refleja cuando registra this._Text , porque tanto Text como _Text se refieren al mismo objeto.
Algo similar ocurre con su segundo bloque de código, antes de ejecutar OuterObject.Text = {Message: "Hello"}; tanto this._Text como this.Text refieren al mismo objeto en la memoria (como lo hicieron en el primer ejemplo), sin embargo, cuando reasignas OuterObject.Text = {Message: "Hello"}; , está creando un nuevo objeto en la memoria ( {Message: "Hello"}; ), y asignando una referencia a ese nuevo objeto a la propiedad .Text , el objeto al que se refiere ._Text ( {Message: "Hi"} ) aún permanece, ya que todo lo que ha hecho es actualizar .Text para apuntar a un nuevo objeto, y no ha cambiado la referencia u objeto this._Text .
Para explicar en diagramas, en ambos bloques de código, inicialmente tiene lo siguiente:
En su primer bloque de código, cuando hace OuterObject.Text["Message"] = "Hello"; , está actualizando el único objeto en la memoria al que this.Text y this._Text , lo que significa que cuando ve this._Text.Message ve "Hello" y lo mismo con this.Text.Message :
En su segundo bloque de código, el primer diagrama/situación todavía ocurre pero el segundo no, en cambio, cuando ejecuta OuterObject.Text = {Message: "Hello"}; obtienes la siguiente estructura:
Arriba, this.Text apunta a un nuevo objeto creado en la memoria, mientras que this._Text aún apunta al objeto anterior, ya que el puntero de this._Text no cambia. Así que registrando this._Text todavía muestra "Hi"