简体   繁体   中英

Javascript function scope when passing object as a parameter

Hi I have the following javascript code

var skyrimCity = function(object) {
    object = {
      'world': 'whiterun'
    };
  },
  skyrim = function(object) {
    object.world = 'skyrim';
  },

  elderScrolls = {
    'world': 'tamriel'
  };
console.log(elderScrolls); // printed value ? -> {world: "tamriel"}

skyrimCity(elderScrolls);
console.log(elderScrolls); // printed value ? -> {world: "tamriel"}

skyrim(elderScrolls);
console.log(elderScrolls); // printed value ? -> {world: "skyrim"}

Inside skyrim function I changed the value of world but I can see it outside the function as well. I am wondering why the scope of this change propagated outside the function? Is passing an object inside a javascript function always passed as a reference to the original object itself?

Is passing an object inside a javascript function always passed as a reference to the original object itself?

Yes, pretty much. In JavaScript, anything that's not a primitive type (number, boolean, string) is a reference type. If you pass an object into a function, you are passing a reference to the original object. If that object is modified inside a function, the original object is modified.

In other words, this has nothing to do with variable scope but rather with what the variables are actually referring to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM