簡體   English   中英

Javascript在函數內部使對象文字等於{},

[英]Javascript make object literal equal {} inside in the function,

如何理解此輸出?

為什么data.value仍然等於'value'?

 function funcA(data) { data.key = 'data'; } function funcB(data) { data = {}; data.value = 'data'; } var data = { key: 'key', value: 'value' }; funcA(data); funcB(data); console.log(data.key); //data console.log(data.value); //value 

請幫忙。 我不知道如何理解這個問題。 感謝您的提前幫助。

您必須了解如何在JavaScript函數中傳遞對象。 它是對要傳遞的內存中對象的引用。 一旦你這樣做data = {}funcB ,該函數的局部參考的復制 data現在指向一個新的空對象,而不是原來的位置data作為函數的定義之外。 然后,行data.value = 'data'只是修改該本地的空對象,而不是原始對象。

data = {}; 只是更新本地參數,而不是原始變量。

如果JS是一種“按引用傳遞”語言,那會起作用,但事實並非如此。 您傳遞的是“引用類型” ,但傳遞的是“按值” ,因此只有值(對象的引用)被更新為新實例。

參數是通過值傳遞的,但是參數的名稱與值不同。 funcB()您會發生一些令人困惑的事情,因為名稱都是相同的。

function funcB(data) {
  // the **name** `data` is not the same as the data you declared earlier
  // even though they both point to the same object
  // this inner data shadows the outer data

  data = {};
  // now you set the inner `data` name to point to a new object and you have two datas
  // one outside that you set with var data and this one. Since you can only have one
  // data name in the scope the inner one wins.
  data.value = 'data';
  // changing data here only changes the inner one.
}

如果您使用不同的名稱,則更加容易:

 function funcB(inner_data) { // the name inner_data and data both point to the same object console.log(inner_data === data) // now inner_data points to something else inner_data = {}; inner_data.value = 'data'; } var data = { key: 'key', value: 'value' }; funcB(data); console.log(data.key); //data console.log(data.value); //value 

之所以會造成混亂,是因為如果您不命名參數data您仍然可以從該函數訪問外部data 例如:

 function funcB(inner_data) { // the name inner_data and data both point to the same object console.log(inner_data === data) // but since you're not shadowing the outer data with // a new name in this scope you can still reach outer data data = {}; data.value = 'data'; } var data = { key: 'key', value: 'value' }; funcB(data); console.log(data.key); //data console.log(data.value); //value 

首先,您應該已經知道,當您將對象分配給變量時,此變量將在內存中保存對該對象數據的引用

引用不過是存儲位置,因此我們知道對象數據的存儲位置

js有一個叫做“通過共享調用”的東西,我很難低估它,但是經過一番搜索之后,我的結論是:

如果您只是在函數作用域內更改了對象的屬性 ,則它將全局影響該變量(在函數作用域之外),這是因為u更改了該變量所引用的對象的值,而不是引用本身,例如funcA

除非您為該變量重新分配了一個新對象 ,否則在這種情況下,您將更改變量引用的位置,該變量現在引用的是其他內容,因此您在函數內部對其所做的任何更改都不會影響函數funcB之外的變量值不會全局影響變量(在函數作用域之外),因為它會創建一個具有新引用的新本地對象,該引用僅作用於該函數

至於原始類型,它們將始終按值傳遞,因此對它們進行的任何更改只會影響進行更改的函數范圍內的變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM