0

Sample Function which is accepting object as parameter and modifying the object property in two different ways. First by using . (dot) notation which is reflected outside function call and second with creating new hash.

function myFunc(theObject) 
{   
    theObject.make = "Toyota";
    theObject = {make: "Ford", model: "Focus", year: 2006};
        console.log(theObject.make); // logs "Ford" 
} 
var mycar = {make: "Honda", model: "Accord", year: 1998}; 
    console.log(mycar.make); // logs "Honda" 
myFunc(mycar); // Call function to change the 'make' 
    console.log(mycar.make); // logs "Toyota"
  1. What is the difference in theObject.make = "Toyota" and theObject = {make:'Ford'}
  2. Why "Toyota" is visible outside function and not "Ford"
Chandre Gowda
  • 870
  • 1
  • 7
  • 24
  • 3
    This has *nothing* to do with scoping. Here is the secret: *objects are not copied/cloned/duplicated* when they are assigned, returned, or passed as arguments. – user2864740 Dec 25 '13 at 05:25
  • Got information like "Assigning a new object to the parameter will not have any effect outside the function, because this is changing the value of the parameter rather than the value of one of the object's properties" – Chandre Gowda Dec 25 '13 at 05:27
  • passing object gets passed as references thus modifying their properties does gets reflected. But when u create a new object as in your second object you changed the reference the `theObject` is referencing and thus its changes are not reflected outside. It is not related to function scope but the way of passing of objects to functions. – guleria Dec 25 '13 at 05:28
  • That refers to [*reassigning* a value to a parameter](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language?lq=1), not *changing* the property of an *object* accessible ("named") by a parameter. – user2864740 Dec 25 '13 at 05:28
  • Place `console.log(theObject)` at the beginning, middle, and end of `myFunc`. The addresses printed might be a hint. – Trojan Dec 25 '13 at 06:32

1 Answers1

0

You are calling myFunc(mycar) function passing the reference of object. when you are doing

theObject.make = "Toyota";

you are changing the value(i.e. Object state) directly, where the object is stored. when again you are creating object the same reference to point to new object, which scope is limited to the function. Oustide the myFunc(mycar): the existing reference still is pointing to the old object, where the object state was changed by function myFunc(theObject)

In a nutshell:

theObject.make = "Toyota"; //Here we are changing the state
theObject = {make: "Ford", model: "Focus", year: 2006};// Here we are crating new Object

Scope is limited to the function.

the difference in theObject.make = "Toyota" chaing existing object state and theObject = {make:'Ford'} is creating new object

Premraj
  • 72,055
  • 26
  • 237
  • 180