2018/02/08
Call by value
Call by reference
Call by sharing (Call by address)
// pseudo code
var a = 'hello world',
b = a;
// pseudo code
var a = 'hello world',
b = a;
// pseudo code
var a = 'hello world',
b = a;
(Call By Address)
// pseudo code
var a = 'hello world',
b = a;
Primitives: Call By Value
Objects: Call By Reference
var str = 'hello world';
changeStr(str);
console.log(str); // 'hello world'
function changeStr(str) {
str = 'hi world'; // assign with literal
}var obj = { prop: "hello world" };
changeObj(obj);
console.log(obj); // { prop: "hi world" }
function changeObj(obj) {
obj.prop = 'hi world';
}How about objects with literal ?
var obj = { prop: "hello world" };
changeObj(obj);
console.log(obj); // { prop: "hi world" }
function changeObj(obj) {
obj = { prop: "hi world" }; // assign with literal
}So, what's the key point indeed ?
Depends on host environment's implement, but most likely:
Call By Sharing
Primitives Call By Sharing
var str = 'hello world';
changeStr(str);
console.log(str); // 'hello world'
function changeStr(str) {
str = 'hi world'; // assign with literal
}Primitives Call By Sharing
Why myth ?
Primitives can only assign to new literal
Objects Call By Sharing
var obj = { prop: "hello world" };
changeObj(obj);
console.log(obj); // { prop: "hi world" }
function changeObj(obj) {
obj.prop = 'hi world';
}Objects Call By Sharing
var obj = { prop: "hello world" };
changeObj(obj);
console.log(obj); // { prop: "hello world" }
function changeObj(obj) {
obj = {};
}Objects Call By Sharing
Why myth ?
Property assign to new literal, not object
var obj = { prop1: 'hi', prop2: 'yo' },
arr = [];
arr.push(obj);
arr.push(obj);
arr[0] = 'yo';
console.log(arr);var obj = { prop1: 'hi', prop2: 'yo' },
arr = [];
arr.push(obj);
arr.push(obj);
arr[0].prop1 = 'yo'
console.log(arr);var a = { x:1 },
p = a.x;
p = 2;
console.log(a.x);