JavaScript

Argument Passing 

2018/02/08

Read From:

Common mechanisms

Call by value

Call by reference

Call by sharing (Call by address)

Call By Value

// pseudo code
var a = 'hello world',
    b = a;

Call By Value

// pseudo code
var a = 'hello world',
    b = a;

Call By Reference

// pseudo code
var a = 'hello world',
    b = a;

Call By Sharing

(Call By Address)

// pseudo code
var a = 'hello world',
    b = a;

Myth

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';
}

Myth

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
}

Myth

So, what's the key point indeed ?

The Truth

Depends on host environment's implement, but most likely:

Call By Sharing

The Truth

Primitives Call By Sharing

var str = 'hello world';

changeStr(str);
console.log(str);        // 'hello world'

function changeStr(str) {
    str = 'hi world';    // assign with literal
}

The Truth

Primitives Call By Sharing

Why myth ?

Primitives can only assign to new literal

The Truth

Objects Call By Sharing

var obj = { prop: "hello world" };

changeObj(obj);
console.log(obj);        // { prop: "hi world" }

function changeObj(obj) {
    obj.prop = 'hi world';
}

The Truth

Objects Call By Sharing

var obj = { prop: "hello world" };

changeObj(obj);
console.log(obj);        // { prop: "hello world" }

function changeObj(obj) {
    obj = {};
}

The Truth

Objects Call By Sharing

Why myth ?

Property assign to new literal, not object

More Examples

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);
Made with Slides.com