简体   繁体   English

将对象作为参数传递时的Javascript函数作用域

[英]Javascript function scope when passing object as a parameter

Hi I have the following javascript code 嗨,我有以下javascript代码

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? 是否始终在javascript函数内传递对象作为对原始对象本身的引用?

Is passing an object inside a javascript function always passed as a reference to the original object itself? 是否始终在javascript函数内传递对象作为对原始对象本身的引用?

Yes, pretty much. 是的,差不多。 In JavaScript, anything that's not a primitive type (number, boolean, string) is a reference type. 在JavaScript中,任何不是原始类型(数字,布尔值,字符串)的东西都是引用类型。 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. 换句话说,这与变量作用域无关,而与变量实际指的是什么有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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