ค้นหาเว็บไซต์

javascript - ฉันจะเปลี่ยนค่าของตัวแปรระดับโลกภายในฟังก์ชันได้อย่างไร


ฉันกำลังใช้ JavaScript และฉันสร้างตัวแปรทั่วโลก ฉันกำหนดตัวแปรนี้นอกฟังก์ชัน และฉันต้องการเปลี่ยนค่าตัวแปรทั่วโลกจากภายในฟังก์ชันและใช้งานมันจากฟังก์ชันอื่น ฉันจะทำอย่างไรดี?

คำตอบ #1

เพียงแค่อ้างอิงตัวแปรภายในฟังก์ชัน; ไม่มีเวทมนตร์ แค่ใช้ชื่อตัวแปรนั้น หากมันถูกสร้างขึ้นแบบ global คุณก็จะกำลังอัปเดตตัวแปร global นั้น

คุณสามารถแทนที่พฤติกรรมนี้ได้โดยการประกาศมันภายในท้องถิ่นโดยใช้ var แต่ถ้าคุณไม่ใช้ var ชื่อของตัวแปรที่ใช้ในฟังก์ชันจะเป็นตัวแปรแบบทั่วโลกหากตัวแปรนั้นถูกประกาศแบบทั่วโลกแล้ว

นั่นคือเหตุผลว่าทำไมจึงถือว่าเป็นแนวทางปฏิบัติที่ดีที่จะประกาศตัวแปรของคุณอย่างชัดเจนด้วย var เพราะถ้าคุณลืมทำ คุณอาจเริ่มยุ่งกับตัวแปรทั่วโลกโดยไม่ได้ตั้งใจ ซึ่งเป็นความผิดพลาดที่ทำได้ง่าย แต่ในกรณีของคุณ เรื่องนี้กลับกลายเป็นคำตอบง่าย ๆ ต่อคำถามของคุณ

คำตอบ #2

var a = 10;

myFunction();

function myFunction(){
   a = 20;
}

alert("Value of 'a' outside the function " + a); //outputs 20

คำตอบ #3

เพียงใช้ชื่อของตัวแปรนั้น

ใน JavaScript ตัวแปรจะเป็นเพียงตัวแปรท้องถิ่นของฟังก์ชันเท่านั้น หากพวกมันเป็นพารามิเตอร์ของฟังก์ชันหรือหากคุณประกาศให้เป็นตัวแปรท้องถิ่นโดยตรงโดยพิมพ์คำสำคัญ var ก่อนชื่อของตัวแปร

ถ้าชื่อของค่าท้องถิ่นมีชื่อเดียวกับค่าระดับโลก ให้ใช้วัตถุ window

ดู jsfiddle นี้

x = 1;
y = 2;
z = 3;

function a(y) {
  // y is local to the function, because it is a function parameter
  console.log('local y: should be 10:', y); // local y through function parameter
  y = 3; // will only overwrite local y, not 'global' y
  console.log('local y: should be 3:', y); // local y
  // global value could be accessed by referencing through window object
  console.log('global y: should be 2:', window.y) // global y, different from local y ()

  var x; // makes x a local variable
  x = 4; // only overwrites local x
  console.log('local x: should be 4:', x); // local x
  
  z = 5; // overwrites global z, because there is no local z
  console.log('local z: should be 5:', z); // local z, same as global
  console.log('global z: should be 5:', window.z) // global z, same as z, because z is not local
}
console.log('global x: should be 1:', x); // global x
console.log('global y: should be 2:', y); // global y
console.log('global z: should be 3:', z); // global z
a(10)
console.log('global x: should be 1:', x); // global x, unaltered
console.log('global y: should be 2:', y); // global y, unaltered
console.log('global z: should be 5:', z); // global z, overwritten in function a

แก้ไข

กับ ES2015 มีคีย์เวิร์ดอีกสองตัวคือ const และ let ซึ่งก็มีผลต่อขอบเขตของตัวแปรเช่นกัน (มาตรฐานภาษา)

คำตอบ #4

var a = 10;

myFunction(a);

function myFunction(a){
   window['a'] = 20; // or window.a
}

alert("Value of 'a' outside the function " + a); //outputs 20

ด้วย window['variableName'] หรือ window.variableName คุณสามารถแก้ไขค่าของตัวแปรทั่วโลกภายในฟังก์ชันได้

บทความที่เกี่ยวข้อง