Javascript Variable Pass And Copy

Variable Pass

Javascript by value

  • 1 . Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • 2 . Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • 3 . However, changing a property of an object referenced by a variable does change the underlying object.

Example

function f(a,b,c) {
    // Argument a is re-assigned to a new value.
    // The object or primitive referenced by the original a is unchanged.
    a = 3;
    // Calling b.push changes its properties - it adds
    // a new property b[b.length] with the value "foo".
    // So the object referenced by b has been changed.
    b.push("foo");
    // The "first" property of argument c has been changed.
    // So the object referenced by c has been changed (unless c is a primitive)
    c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value
a[2] = "5";   // a is now ["1", "4", "5"]; c still has the value
              // it had at the time of assignment, i.e. a reference to
              // the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"

Variable Copy

Shallow Copy Vs Deep Copy

  • 1 . The = operator is always copy by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • 2 . Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • 3 . However, changing a property of an object referenced by a variable does change the underlying object.

JQuery Method

Shallow Copy

b = $.extend( {}, a );

Deep Copy

 = $.extend( true, {}, a );

Custom Method

var deepCopy= function(source) {   
   var result={};
   for (var key in source) {
      result[key] = typeof source[key]===’object’? deepCoyp(source[key]): source[key];
   } 
   return result; 
}

Array Deep Copy

* js slice method

var arr = ["One","Two","Three"];
var arrtoo = arr.slice(0);
arrtoo[1] = "set Map";
document.writeln("数组的原始值:" + arr + "<br />");//Export:数组的原始值:One,Two,Three
document.writeln("数组的新值:" + arrtoo + "<br />");//Export:数组的新值:One,set Map,Three

* js concat method


var arr = ["One","Two","Three"];
var arrtooo = arr.concat();
arrtooo[1] = "set Map To";
document.writeln("数组的原始值:" + arr + "<br />");//Export:数组的原始值:One,Two,Three
document.writeln("数组的新值:" + arrtooo + "<br />");//Export:数组的新值:One,set Map To,Three
JSRUN notes