JavaScript là pass-by-value. Nhưng với object, value là reference của object.
Ví dụ 1: Primitive (pass by value)
let i = 0;
function increment(x) { x = x + 1; console.log(x); }
increment(i); // 1
console.log(i); // 0 (không thay đổi)
Ví dụ 2: Object (pass reference by value)
let obj = {'foo': 'bar'};
function updateRef(x) { x = {}; } // Thay reference local, không ảnh hưởng obj
function addHelloWorld(y) { y['hello'] = 'world'; } // Mutate object
console.log(obj); // { foo: 'bar' }
updateRef(obj);
console.log(obj); // { foo: 'bar' } - không đổi
addHelloWorld(obj);
console.log(obj); // { foo: 'bar', hello: 'world' } - đã mutate
Giải thích:
- Primitive: truyền bản sao giá trị, thay đổi local không ảnh hưởng gốc
- Object: truyền bản sao reference (con trỏ). Gán lại parameter (
x = {}) chỉ thay reference local. Mutate nội dung (y.hello = 'world') ảnh hưởng object gốc vì cùng trỏ đến 1 địa chỉ heap - Không có pass-by-reference thực sự trong JS