Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript pass object as reference

i have a object, which is getting passed in many different functions inside a function. these functions may or may not change the value of the object, but if they do change it, then i would like to get the latest changes on object.

following is what im trying to do:

var ob = {text: 'this is me', name: 'john'}  function (object) {       changeObject(object);      customObjectChanger(object);      callback = function (object) {           object.text = 'new text';      }       callback(object);       // object value here should be object{text: 'new text', name: 'john'};     } 
like image 267
Basit Avatar asked Jun 02 '13 06:06

Basit


People also ask

Does JavaScript pass object by reference?

In JavaScript array and Object follows pass by reference property. In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value.

Can you pass an object by reference?

A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.

How do you reference an object in JavaScript?

Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object. Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.

Are objects passed by reference in typescript?

Pass in Arguments by ReferenceNon-primitive are passed into a function by reference, which means that the reference to the object passed in as the argument is passed into the function. The copy of the content is not made for the argument and the passed in object is modified directly.


1 Answers

In JavaScript objects are always passed by copy-reference. I'm not sure if that's the exactly correct terminology, but a copy of the reference to the object will be passed in.

This means that any changes made to the object will be visible to you after the function is done executing.

Code:

var obj = {    a: "hello"  };    function modify(o) {    o.a += " world";  }    modify(obj);  console.log(obj.a); //prints "hello world"

Having said that, since it's only a copy of the reference that's passed in, if you re-assign the object inside of your function, this will not be visible outside of the function since it was only a copy of the reference you changed.

Code:

var obj = {    a: "hello"  };    function modify(o) {    o = {      a: "hello world"    };  }    modify(obj);  console.log(obj.a); //prints just "hello"
like image 51
Adam Rackis Avatar answered Oct 05 '22 22:10

Adam Rackis