Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript是按引用传递还是按值传递语言? 原始类型(数字、字符串等)是通过值传递的,但对象是未知的,因为它们都可以通过值传递(如果我们认为持有对象的变量实际上是对对象的引用),并通过引用传递(当我们考虑到对象的变量持有对象本身)时,_Javascript_Pass By Reference_Pass By Value - Fatal编程技术网

JavaScript是按引用传递还是按值传递语言? 原始类型(数字、字符串等)是通过值传递的,但对象是未知的,因为它们都可以通过值传递(如果我们认为持有对象的变量实际上是对对象的引用),并通过引用传递(当我们考虑到对象的变量持有对象本身)时,

JavaScript是按引用传递还是按值传递语言? 原始类型(数字、字符串等)是通过值传递的,但对象是未知的,因为它们都可以通过值传递(如果我们认为持有对象的变量实际上是对对象的引用),并通过引用传递(当我们考虑到对象的变量持有对象本身)时,,javascript,pass-by-reference,pass-by-value,Javascript,Pass By Reference,Pass By Value,虽然这在最后并不重要,但我想知道用什么正确的方式来表示通过约定的参数。是否有来自JavaScript规范的摘录,其中定义了与此相关的语义?有一些关于在JavaScript中使用术语“通过引用传递”的讨论,但为了回答您的问题: 对象是通过引用自动传递的,无需特别声明它 (来自上面提到的文章。)变量不“持有”对象;它有一个参考。您可以将该引用指定给另一个变量,现在两者都引用同一个对象。它总是通过值传递(即使该值是引用…) 无法更改作为参数传递的变量所持有的值,如果JavaScript支持按引用传递,

虽然这在最后并不重要,但我想知道用什么正确的方式来表示通过约定的参数。是否有来自JavaScript规范的摘录,其中定义了与此相关的语义?

有一些关于在JavaScript中使用术语“通过引用传递”的讨论,但为了回答您的问题:

对象是通过引用自动传递的,无需特别声明它

(来自上面提到的文章。)

变量不“持有”对象;它有一个参考。您可以将该引用指定给另一个变量,现在两者都引用同一个对象。它总是通过值传递(即使该值是引用…)

无法更改作为参数传递的变量所持有的值,如果JavaScript支持按引用传递,这是可能的。

JavaScript总是按值传递;一切都是价值型的

对象是值,对象的成员函数本身就是值(记住,函数在JavaScript中是一级对象)。另外,关于JavaScript中的一切都是对象的概念;这是错误的。字符串、符号、数字、布尔值、空值和未定义项都是基元

有时,它们可以利用从基本原型继承的一些成员函数和属性,但这只是为了方便。这并不意味着它们本身就是对象。请尝试以下内容以供参考:

x = "test";
alert(x.foo);
x.foo = 12;
alert(x.foo);

在这两个警报中,您会发现值未定义。

确定某个内容是否为“按引用传递”的简单方法是您是否可以编写“交换”函数。例如,在C中,您可以执行以下操作:

void swap(int *i, int *j)
{
    int t;
    t = *i;
    *i = *j;
    *j = t;
}

如果你不能在JavaScript中做到这一点,那就不是“通过引用传递”。

这在JavaScript中很有趣。考虑这个例子:

函数变换器(a、b、c)
{
a=a*10;
b、 item=“已更改”;
c={项目:“已更改”};
}
var-num=10;
var obj1={item:“unchanged”};
var obj2={item:“unchanged”};
变更对象(num、obj1、obj2);
console.log(num);
控制台日志(obj1.item);

console.log(obj2.item)它总是按值传递,但对于对象,变量的值是一个引用。因此,当您传递一个对象并更改其成员时,这些更改将保留在函数之外。这使它看起来像是通过引用传递的。但是,如果您实际更改了对象变量的值,您将看到更改不会持续,从而证明它确实是通过值传递的

例如:

函数changeObject(x){
x={成员:“条”};
console.log(“in changeObject:+x.member”);
}
功能更改成员(x){
x、 member=“bar”;
console.log(“in changember:+x.member”);
}
var x={成员:“foo”};
console.log(“更改对象之前:+x.member”);
变更对象(x);
console.log(“在changeObject之后:+x.member);/*变化并未持续*/
console.log(“变更前成员:+x.member”);
变更成员(x);

console.log(“变更后成员:+x.member”);/*更改依然存在*/
关于复制、传递和比较的详细说明,请参见“JavaScript:最终指南”一书

在我们离开这个话题之前 通过 参考资料,我们需要澄清一点 命名法

“路过”一词 “reference”可以有多种含义。 对一些读者来说,这个短语指的是 一种函数调用技术 允许函数指定新值 它的论点,并有这些 修改后的值在外部可见 功能。这不是这个术语的用法 这本书中使用了

这里,我们的意思是 简单地说就是对一个对象的引用 或数组,而不是对象本身-- 传递给函数。函数 可以使用引用进行修改 对象或元素的属性 数组的一部分。但是如果函数 用一个 对新对象或数组的引用, 这种修改是不可见的 在功能之外

var myObject = {
    firstName: 'Joe',
    lastName: 'Smith'
};

// Assign to a new variable (just like when you pass to a function)
var otherObj = myObject;

// Let's mutate our object
otherObj.firstName = 'Sue'; // I guess Joe decided to be a girl

console.log(myObject.firstName); // Logs 'Sue'
console.log(otherObj.firstName); // Logs 'Sue'

// Now, let's reassign the variable
otherObj = {
    firstName: 'Jack',
    lastName: 'Frost'
};

// Now, otherObj and myObject are assigned to 2 very different objects
// And mutating one object has no influence on the other
console.log(myObject.firstName); // Logs 'Sue'
console.log(otherObj.firstName); // Logs 'Jack';
读者 熟悉 这个术语可能更倾向于这样说 对象和数组通过 值,但传递的值为 实际上是一个参考,而不是 对象本身


函数外部的对象通过引用外部对象传递到函数中

当您使用该引用操纵其对象时,外部对象将因此受到影响。但是,如果在函数内部决定将引用指向其他对象,则根本不会影响外部对象,因为您所做的只是将引用重新指向其他对象

我发现,当我想将对象作为参数传入时,这个函数非常有用,它可以被修改或完全替换

function replaceOrModify(aObj) {
  if (modify) {

    aObj.setNewValue('foo');

  } else {

   var newObj = new MyObject();
   // _.extend(destination, *sources) 
   _.extend(newObj, aObj);
  }
}
  • 原语(数字、布尔值等)按值传递。
    • 字符串是不可变的,所以这对它们来说并不重要
  • 对象通过引用传递(引用通过值传递)

  • 我发现最简洁的解释是:

    • 基本体:当您访问基本体类型时,您直接在其上工作 价值观

      • 布尔值
      • 空的
      • 未定义
    例如:

    • Complex:访问复杂类型时,处理对其值的引用

      • 反对
      • 排列
      • 作用
    例如:

    也就是说,基本类型实际上是通过值传递的,复杂类型是通过引用传递的。

    我的两分钱。。。这
    var foo = [1, 2],
        bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9
    
    var object1 = {};
    var object2 = {};
    
    var favoriteObject = object1;
    
    favoriteObject = object2;
    
    object2.name = 'Fred';
    console.log(favoriteObject.name) // Logs Fred
    favoriteObject.name = 'Joe';
    console.log(object2.name); // Logs Joe
    
    var string1 = 'Hello world';
    var string2 = 'Goodbye world';
    
    var favoriteString = string1;
    
    favoriteString = 'Hello everyone';
    console.log(favoriteString); // Logs 'Hello everyone'
    console.log(string1); // Logs 'Hello world'
    
    var myString = 'hello';
    
    // Assign to a new variable (just like when you pass to a function)
    var param1 = myString;
    param1 = 'world'; // Re assignment
    
    console.log(myString); // Logs 'hello'
    console.log(param1);   // Logs 'world'
    
    function myFunc(param1) {
        param1 = 'world';
    
        console.log(param1);   // Logs 'world'
    }
    
    var myString = 'hello';
    // Calls myFunc and assigns param1 to myString just like param1 = myString
    myFunc(myString);
    
    console.log(myString); // logs 'hello'
    
    var myObject = {
        firstName: 'Joe',
        lastName: 'Smith'
    };
    
    // Assign to a new variable (just like when you pass to a function)
    var otherObj = myObject;
    
    // Let's mutate our object
    otherObj.firstName = 'Sue'; // I guess Joe decided to be a girl
    
    console.log(myObject.firstName); // Logs 'Sue'
    console.log(otherObj.firstName); // Logs 'Sue'
    
    // Now, let's reassign the variable
    otherObj = {
        firstName: 'Jack',
        lastName: 'Frost'
    };
    
    // Now, otherObj and myObject are assigned to 2 very different objects
    // And mutating one object has no influence on the other
    console.log(myObject.firstName); // Logs 'Sue'
    console.log(otherObj.firstName); // Logs 'Jack';
    
    function myFunc(otherObj) {
    
        // Let's mutate our object
        otherObj.firstName = 'Sue';
        console.log(otherObj.firstName); // Logs 'Sue'
    
        // Now let's re-assign
        otherObj = {
            firstName: 'Jack',
            lastName: 'Frost'
        };
        console.log(otherObj.firstName); // Logs 'Jack'
    
        // Again, otherObj and myObject are assigned to 2 very different objects
        // And mutating one object doesn't magically mutate the other
    }
    
    var myObject = {
        firstName: 'Joe',
        lastName: 'Smith'
    };
    
    // Calls myFunc and assigns otherObj to myObject just like otherObj = myObject
    myFunc(myObject);
    
    console.log(myObject.firstName); // Logs 'Sue', just like before
    
    function myFunc(myString) {
        // myString is private and does not affect the outer variable
        myString = 'hello';
    }
    
    var myString = 'test';
    myString = myString; // Does nothing, myString is still 'test';
    
    myFunc(myString);
    console.log(myString); // Logs 'test'
    
    var var1 = 13;
    var var2 = { prop: 2 };
    
    //13 and var2's content (reference) are being passed here
    foo(var1, var2); 
    
    function foo(inVar1, inVar2){
        //changing contents of inVar1 and inVar2 won't affect variables outside
        inVar1 = 20;
        inVar2 = { prop: 7 };
    }
    
    function foo(inVar1, inVar2){
        inVar2.prop = 7; 
    }
    
        function passVar(object1, object2, number1) {
    
            object1.key1= "laptop";
            object2 = {
                key2: "computer"
            };
            number1 = number1 + 1;
        }
    
        var object1 = {
            key1: "car"
        };
        var object2 = {
            key2: "bike"
        };
        var number1 = 10;
    
        passVar(object1, object2, number1);
        console.log(object1.key1);
        console.log(object2.key2);
        console.log(number1);
    
    Output: -
        laptop
        bike
        10
    
    /*
    The following C program demonstrates how arguments
    to JavaScript functions are passed in a way analogous
    to pass-by-pointer-value in C. The original JavaScript
    test case by @Shog9 follows with the translation of
    the code into C. This should make things clear to
    those transitioning from C to JavaScript.
    
    function changeStuff(num, obj1, obj2)
    {
        num = num * 10;
        obj1.item = "changed";
        obj2 = {item: "changed"};
    }
    
    var num = 10;
    var obj1 = {item: "unchanged"};
    var obj2 = {item: "unchanged"};
    changeStuff(num, obj1, obj2);
    console.log(num);
    console.log(obj1.item);    
    console.log(obj2.item);
    
    This produces the output:
    
    10
    changed
    unchanged
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    struct obj {
        char *item;
    };
    
    void changeStuff(int *num, struct obj *obj1, struct obj *obj2)
    {
        // make pointer point to a new memory location
        // holding the new integer value
        int *old_num = num;
        num = malloc(sizeof(int));
        *num = *old_num * 10;
        // make property of structure pointed to by pointer
        // point to the new value
        obj1->item = "changed";
        // make pointer point to a new memory location
        // holding the new structure value
        obj2 = malloc(sizeof(struct obj));
        obj2->item = "changed";
        free(num); // end of scope
        free(obj2); // end of scope
    }
    
    int num = 10;
    struct obj obj1 = { "unchanged" };
    struct obj obj2 = { "unchanged" };
    
    int main()
    {
        // pass pointers by value: the pointers
        // will be copied into the argument list
        // of the called function and the copied
        // pointers will point to the same values
        // as the original pointers
        changeStuff(&num, &obj1, &obj2);
        printf("%d\n", num);
        puts(obj1.item);
        puts(obj2.item);
        return 0;
    }
    
    function changePrimitive(val) {
        // At this point there are two '10's in memory.
        // Changing one won't affect the other
        val = val * 10;
    }
    var x = 10;
    changePrimitive(x);
    // x === 10
    
    function changeObject(obj) {
        // At this point there are two references (x and obj) in memory,
        // but these both point to the same object.
        // changing the object will change the underlying object that
        // x and obj both hold a reference to.
        obj.val = obj.val * 10;
    }
    var x = { val: 10 };
    changeObject(x);
    // x === { val: 100 }
    
    function changeObject(obj) {
        // Again there are two references (x and obj) in memory,
        // these both point to the same object.
        // now we create a completely new object and assign it.
        // obj's reference now points to the new object.
        // x's reference doesn't change.
        obj = { val: 100 };
    }
    var x = { val: 10 };
    changeObject(x);
    // x === { val: 10}
    
    // code
    var obj = {
        name: 'Fred',
        num: 1
    };
    
    // illustration
                   'Fred'
                  /
                 /
    (obj) ---- {}
                 \
                  \
                   1
    
    // code
    obj.name = 'George';
    
    
    // illustration
                     'Fred'
    
    
    (obj) ---- {} ----- 'George'
                 \
                  \
                   1
    
    // code
    obj = {};
    
    // illustration
                     'Fred'
    
    
    (obj)      {} ----- 'George'
      |          \
      |           \
     { }            1
    
    // code
    var obj = {
        text: 'Hello world!'
    };
    
    /* function parameters get their own pointer to 
     * the arguments that are passed in, just like any other variable */
    someFunc(obj);
    
    
    // illustration
    (caller scope)        (someFunc scope)
               \             /
                \           /
                 \         /
                  \       /
                   \     /
                     { }
                      |
                      |
                      |
                'Hello world'
    
    var a = [1,2];
    var b = a;
    
    a = [];
    console.log(b); // [1,2]
    // doesn't work because `b` is still pointing at the original array
    
    var a = 2;
    var b = a; // `b` is always a copy of the value in `a`
    b++;
    a; // 2
    b; // 3
    
    var c = [1,2,3];
    var d = c; // `d` is a reference to the shared `[1,2,3]` value
    d.push( 4 );
    c; // [1,2,3,4]
    d; // [1,2,3,4]
    
    var a = [1,2,3];
    var b = a;
    a; // [1,2,3]
    b; // [1,2,3]
    
    // later
    b = [4,5,6];
    a; // [1,2,3]
    b; // [4,5,6]
    
    function foo(x) {
        x.push( 4 );
        x; // [1,2,3,4]
    
        // later
        x = [4,5,6];
        x.push( 7 );
        x; // [4,5,6,7]
    }
    
    var a = [1,2,3];
    
    foo( a );
    
    a; // [1,2,3,4]  not  [4,5,6,7]
    
    foo( a.slice() );
    
    function foo(wrapper) {
        wrapper.a = 42;
    }
    
    var obj = {
        a: 2
    };
    
    foo( obj );
    
    obj.a; // 42
    
    int myAge = 14;
    increaseAgeByRef(myAge);
    function increaseAgeByRef(int &age) {
      *age = *age + 1;
    }
    
    var a = 3;
    var b = a;
    
    console.log(a); // a = 3
    console.log(b); // b = 3
    
    a=4;
    console.log(a); // a = 4
    console.log(b); // b = 3
    
    var c = { "name" : "john" };
    var d = c;
    
    console.log(c); // { "name" : "john" }
    console.log(d); // { "name" : "john" }
    
    c.name = "doe";
    
    console.log(c); // { "name" : "doe" }
    console.log(d); // { "name" : "doe" }
    
    c = {"name" : "jane"};
    console.log(c); // { "name" : "jane" }
    console.log(d); // { "name" : "doe" }
    
    let arr = [1, 2, 3, 4, 5]; //arr is an object now and a purple arrow is indicating it
    let obj2 = arr; // now, obj2 is another purple arrow that is indicating the value of arr obj
    let obj3 = ['a', 'b', 'c'];
    obj2.push(6); // first pic below - making a new hand for the blue circle to point the 6
    //obj2 = [1, 2, 3, 4, 5, 6]
    //arr = [1, 2, 3, 4, 5, 6]
    //we changed the blue circle object value (type1-value) and due to arr and obj2 are indicating that so both of them changed
    obj2 = obj3; //next pic below - changing the direction of obj2 array from blue circle to orange circle so obj2 is no more [1,2,3,4,5,6] and it's no more about changing anything in it but we completely changed its direction and now obj2 is pointing to obj3
    //obj2 = ['a', 'b', 'c'];
    //obj3 = ['a', 'b', 'c'];
    
    // Copy JS object without reference
    var first = {"a":"value1","b":"value2"};
    var clone = JSON.parse( JSON.stringify( first ) ); 
    
    var second = ["a","b","c"];
    var clone = JSON.parse( JSON.stringify( second ) ); 
    
     let a = { prop: 1 };
     let b = a; // a and b hold the same value
     a.prop = "test"; // The object gets mutated, can be observed through both a and b
     b = { prop: 2 }; // b holds now a different value