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

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

What is the process for running "node server.js" within codelab?

I am currently going through a codelab tutorial on Bitbucket at this link After installing node.js for the first time, I encountered an error when trying to run the server.js file: node server.js The error message "node: Command not found" appeared even ...

What steps do I need to take to ensure NextJS stores my edits in VSCode?

I have attempted various troubleshooting steps such as changing file extensions from .js to .jsx, turning on Prettier for formatting upon saving, setting it as the default formatter, reloading and restarting the editor. However, the issue with not being ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

Chosen Dropdown selection - Retrieve/Receive information

One of the challenges I'm facing involves a dropdown list on my web form that contains various dates. My main query is: How can I retrieve data for the selected date from a MySQL database and present it to the user? Additionally, if the chosen date do ...

Ways to display JSON data in Angular 2

My goal is to display a list of JSON data, but I keep encountering an error message ERROR TypeError: Cannot read property 'title' of undefined. Interestingly, the console log shows that the JSON data is being printed. mydata.service.ts import { ...

How can JavaScript be used to make an AJAX request to a server-side function?

I am diving into the world of AJAX and feeling a bit uncertain about how to structure my AJAX call. $.ajax({ type: "POST", url: "Default.aspx/function", data: '{ searchBy: id }', contentType: "application/json; charset=utf-8" }). ...

Using Vue's $set method to update nested JSON values

[ { "id": 1, "question": "Main Inquiry", "answers": [ {"id" : 1, "isSelected" : false}, {"id" : 2, "isSelected" : true}, {"id" : 3, "isSelected" : false}, {"id" : 4, "isSelected" : false}, {"id" : 5, "isSel ...

Creating a unique filter that combines and filters data from two separate API calls for

In my current scenario, I am making two different API calls using Axios in my application. The first call fetches a complete JSON file that populates a table, while the second call retrieves only categories. This setup is due to the complexity of the app, ...

What is the process for updating the Vue template during runtime?

Currently, I am working on a CMS-based Vue page. Within this page, there is a root container that contains two child containers structured as follows: <div id="app"> <div class="above-the-fold">...</div> <di ...

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly ins ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Struggling to retrieve Json data through Ajax in Rails 5

Hey there! I'm currently exploring the world of Rails action controllers with Ajax, and I've run into a bit of a snag. I can't seem to retrieve Json data and display it in my console.log using my Ajax function. The GET method works perfectly ...

Guide on implementing router-link within a select option dropdown in a Vue.js application

a.vue <template> <div>hi i am component 1</div> </template> <script> export default { name: "a", }; </script> b.vue <template> <div>hi i am component 2</div> </template> <script> ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

Troubleshooting AngularJS: Diagnosing Issues with My Watch Functionality

I need to set up a watch on a variable in order to trigger a rest service call whenever its value changes and update the count. Below is the code snippet I have: function myController($scope, $http) { $scope.abc = abcValueFromOutsideOfMyController; ...

What is the best way to define a variable in EJS?

I need to populate my database array results on the frontend using EJS. The code snippet I'm using is as follows: var tags = ["<%tags%>"] <% for(var i=0; i<tags.length; i++) { %> <a href='<%= tags[i] %&g ...

How to generate a list in Vue.js using an array

I am facing an unusual issue while trying to create a list using Vuejs. Here is the structure of my array: const sr = new Vue({ el: '#singlerecipe-app', data: { checkeditems: [], }, }); This array is initialized in my HTML as follows: ...