Is it the same item in one situation, but a completely different item in another?

I am currently investigating the behavior of objects in JavaScript, particularly when it comes to copying one object onto another. It seems that sometimes they behave as if they are the same object, where modifying one also modifies the other. Many resources mention that JavaScript objects are duplicated by reference, essentially making them identical. An example from http://www.w3schools.com/js/js_object_definition.asp demonstrates this:

 var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"} 
 var x = person;  
 x.age = 10;

 The object x is not a copy of person. It is person. Both x and person
 are the same object. Any changes to x will also change person, because
 they refer to the same object.

Interestingly, I have come across instances where objects seem to act independently. How can an object appear as the same entity in one scenario and a distinct one in another? I would appreciate any insights on this matter:

Example: http://codepen.io/gratiafide/pen/yagQGr?editors=1010#0

HTML:

<div id="app">
  <my-component>
  </my-component>
</div>

JS:

  var MyComponent = Vue.extend({
  template: '<div v-on:click="test()" class="red">1. Click here to copy the name object to message and change the value of name to see if the value of message gets changed also. (It does not).</div>  message: {{ message | json}} <br> name: {{ name | json}}<div v-on:click="test2()" class="red">2. Now click here to see if updating the name object also changes the message object. It does! Why here and not in #1?</div><div v-on:click="test3()" class="red">3. Click here to see yet another way of updating the name object also changes the message object. Why here and not in #1?</div>',

  data: function () {
    return { 
    message: {},
    name: {}
    }
  },

  ready: function(){
    this.message = {};
  },
  methods: {
    test: function(){
       this.message = {'t1':"m1"};
       this.name = this.message;  
       this.name = {'t2':"m2"};  
    },
    test2: function(){
       this.message = {'t1':"m1"};
       this.name = this.message;  
       for (var key in this.name) {
                this.name[key] = '';
            }  
    },
    test3: function(){
       this.message = {'t1':"m1"};
       this.name = this.message;  
       Vue.set(this.name, 't1', 'm2');
    }
  }
});

Vue.component('my-component', MyComponent);

new Vue({
  el: '#app'
});

CSS:

@import url(https://fonts.googleapis.com/css?family=Open+Sans);

.red{
  color:red;  
}

body {
  font-family: 'Open Sans', sans-serif;
  background: rgba(0,0,0,.5);
  margin: 0;
}

#app {
  width: 500px;
  margin: 0 auto;
  padding: 10px 20px;
  background: rgba(255,255,255,.9);
}

Answer №1

Essentially, you are inquiring about the distinctions between these three scenarios:

this.message = {'t1':"m1"};
this.name = this.message;  

#1:
this.name = {'t2':"m2"};  

#2
for (var key in this.name) {
  this.name[key] = '';
}  

#3
Vue.set(this.name, 't1', 'm2');

In the first scenario, this.message will not change because you are assigning an entirely new object to this.name. This new object ({'t2':"m2"}) has no relation to this.message.

Perhaps what you were attempting or thinking of doing was:

this.name.t2 = "m2";

This achieves the same outcome as #2 and #3, impacting this.message, since this.name still points to the same object.

To add new properties from one object into another existing object, you can utilize the Object.assign method in browsers that support it:

Object.assign(this.name, {'t2':"m2"});

Answer №2

Two categories of variables exist: value and reference. All primitive types (such as strings, numbers, and booleans) are stored by value, while everything else is stored by reference and can have properties.

var a,b;
a={c:1};
b=a;
console.log (b===a); // true;

b={c:1}; // note that b now references a new location.
console.log (b===a); // false;

a=b; // a now points to the same location as b.
console.log (b===a); // true;

a.c=2; // the property of a (c) has changed, not a itself.
console.log (b===a); // true;

a.a = a; // a now contains a property (a) referencing itself.
console.log(a === a.a);
console.log(a.a === a.a.a);
console.log(a.a === a.a.a.a.a.a.a.a.a);
a.a.a.a.a.a.a.a.a.a.a.c = 10;
console.log(a.c)//10;
Different methods for declaring variables exist, but that is beyond the scope of this discussion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rendering elements dynamically using ng-repeat following an AJAX request

Feeling frustrated, I made an $http request ApiService.get_request_params("api/endpoint").then( function(data) { $scope.customers = data }, function(err) { } ); The $scope.customers should be bound to an ng-repeat. I can see the ...

Is there a built-in function in Firefox that can retrieve a list of all indexedDB names stored in the

When working in chrome, I utilized the window.indexedDB.databases() method to retrieve all indexedDb names. However, this same method does not seem to be functioning in firefox. In an attempt to resolve this issue, I will explore alternative methods such ...

Building custom components in Vue.js/NuxtJS can be a breeze when using a default design that can be easily customized through a JSON configuration

Currently, I am in the process of developing a NuxtJS website where the pages and components can either have a generic design by default or be customizable based on client specifications provided in the URL. The URL structure is as follows: http://localh ...

Unusual naming problem encountered in DataTables when employing diverse functions

I'm encountering an unusual issue with DataTables. In the documentation, there is inconsistency in using either a capital D or lowercase d when referring to the class name: var table = $('#example').DataTable(); Sometimes it's like th ...

The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from f ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

Styling the active selection in nav class with bold attribute in Bootstrap/AngularJs

How can I apply the bold attribute to the currently selected nav bar item? <ul class="nav"> <li role="presentation" ng-repeate="item in items" ng-class="{'active':navLink == item.header}"> </li> &l ...

``"Selecting a location upon clicking a marker in the array

I have limited experience with javascript but I am determined to improve my skills. Currently, I am facing a major roadblock in a project that I am working on and urgently require assistance. The project involves creating a map with marked locations from ...

Setting up Vue.js for development

I am in the process of creating a client application with Vue.js, but I am currently grappling with a crucial question: How can I obtain the address of my backend service? There is one major requirement for the solution to this issue: The final build arti ...

The mystery of the Accordion Effect: A Next.js/React.js issue where it slides up but refuses to

After implementing a custom accordion using next.js, I encountered an issue where the slide animation worked successfully when moving up and out upon clicking the button. However, when trying to move it back down into the content, it did not animate as exp ...

Error encountered in VUE JS 3: The function vue.initDirectivesForSSR is not recognized as a valid function

I've been encountering some errors while trying to build my Vue web app with this configuration. I have searched for a solution, but couldn't find anyone facing the same issue as me. Any suggestions on how to resolve this problem? The build was s ...

How to retrieve the index of a table row in Vue with Element UI?

Is there a way to add a button only to the first row of a table column (labeled as 'Option' in the example code) and check the row index using v-if="scope.row.index === 0"? The current method with scope.row.index is not working. <el- ...

Activate plugin automatically for all Vue instances

Can a plugin be automatically loaded for every instance of new Vue()? I am utilizing a library that generates its own Vue instances and I require a specific plugin to be added to each one. ...

Refining the options in security question dropdown menus

Firstly: The title should mention filtering security options in dropdown lists, but it seems I'm restricted from using the term questions or question in the title. I came across this code example, but it appears to be outdated. Does anyone know why a ...

Warning triggered Grunt cancellation

I've successfully installed "npm" on my local machine. When it comes to installing grunt in my Gruntfile.js directory, I follow these steps: npm install grunt npm install -g grunt-cli grunt watch Although the tasker is up and running, I en ...

What is the best way to create a function that requires an argument in TypeScript?

I'm looking to bring in a module that requires an argument in Typescript. This is how it looks in javascript: const cors = require('cors')({origin: true}); // JS What would be the equivalent syntax in Typescript? ...

Creating a stylish zebra pattern using JCrop on the cropping window

Lately, while using jquery jcrop, I've noticed a peculiar design appearing on the cropping window. The details of this pattern are unclear to me. What could be the reason behind the zebra-like pattern visible on the cropping window? Is there any spec ...

The data received by request.responseText is accurate, however JavaScript is unable to interpret it

I am currently diving into the world of AJAX and educating myself using Head First AJAX. I have encountered a strange issue while working on a simple program that makes a request using JavaScript and displays the output. main.js window.onload = initPage; ...

When attempting to make an AJAX call using the console, an error was encountered stating that the function $.ajax is not available

Currently experimenting with an ajax call from my console to a local server, but encountering an error: VM4460:1 Uncaught TypeError: $.ajax is not a function(…) Here's the code snippet causing the issue: url = 'http://localhost:8080/testform ...

Discovering the process of retrieving information from Firebase using getServerSideProps in NextJs

I've been exploring ways to retrieve data from Firebase within GetServerSideProps in NextJs Below is my db file setup: import admin from "firebase-admin"; import serviceAccount from "./serviceAccountKey.json"; if (!admin.apps.len ...