Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cơ chế "Pass by Value" trong JavaScript

JavaScript luôn pass-by-value (truyền theo giá trị). Với object, **giá trị là reference**.

Primitive (số, chuỗi, boolean...)

let i = 0;
function increment(x) { x = x + 1; console.log(x); }
increment(i); // 1
console.log(i); // 0

Giá trị được copy, thay đổi trong hàm không ảnh hưởng biến ngoài.

Object

let obj = { foo: 'bar' };

function updateRef(x) { x = {}; }           // gán lại reference local
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' } (mutated)

Giải thích

  • x = {}: biến local x trỏ object mới → object gốc không đổi.
  • y.hello = 'world': y cùng reference với obj → mutate object gốc.

Đây là mô hình Call by Sharing — không phải pass-by-reference thuần túy.