Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript เป็น Pass-by-Reference หรือ Pass-by-Value

JavaScript เป็นภาษา Pass by Value แต่สำหรับ Objects ค่าคือ Reference ของมัน ตัวอย่าง: ส่ง int ให้ Function เป็น Parameter และเพิ่มค่าใน Function ค่าไม่เปลี่ยนใน Caller Context

ตัวอย่าง

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

ผลลัพธ์

1 0

ส่ง Object และ Update Reference ใน Function Context ไม่ส่งผลต่อ Object แต่หาก Mutate Internal ของ Object จะสะท้อนใน Object เดิม

ตัวอย่าง

let obj = {'foo': 'bar'}; function updateRef(x) {    x = {} } function addHelloWorld(y) {    y['hello'] = 'world'; } console.log(obj) updateRef(obj) console.log(obj) addHelloWorld(obj) console.log(obj)

ผลลัพธ์

{ foo: 'bar' } { foo: 'bar' } { foo: 'bar', hello: 'world' }

การเปลี่ยน Reference ของ Object ไม่ส่งผลต่อ Object เดิม ตัวแปร Local x ถูก Reassign ใน Function ที่สอง y Reference ไปที่ obj เดียวกัน Mutate Internal State จึงส่งผลต่อ Original Object