[英]Can users manipulate values from read-only fields using javascript or any other way?
[英]Are import values disconnected from their export values still read-only?
給出了以下模塊結構:
// module A:
export let a = 1; // named export
export function inc() { a++; } // named export
// module B:
let b = 1;
export default b; // default export (equivalent to `export default 1`)
export function inc() { b++; } // named export
// module C:
let c = {};
export default c; // default export
// module E:
import a, {inc as incA} from "./A";
import b, {inc as incB} from "./B";
import c from "./C";
incA();
console.log(a); // logs 2, because "a" has a live connection to the export value
a++; // Error (because a is a live read-only view on the export)
incB();
console.log(b); // logs 1, because "b" is disconnected from the export value
b++; // Does this throw an error as well?
c.prop = true; // I think mutations are always allowed, right?
c = {}; // but are reassignment allowed too?
如果我有一個表達式的默認導出( export default b
或export default 1
),則相應的導入與此導出值斷開連接。 考慮到這一點,這樣的導入是否仍然是只讀的,也就是說,我可以重新分配a
或c
嗎?
導入綁定始終是只讀的,請參閱規范中的抽象CreateImportBinding
操作,步驟 5:
- 在envRec 中為N創建一個不可變的間接綁定,引用M和N2作為其目標綁定,並記錄綁定已初始化。
(我的重點)
該操作由ModuleDeclarationInstantiation
在處理模塊的導入條目時使用。
所以:
b++; // Does this throw an error as well?
是的, b
是只讀的。
c.prop = true; // I think mutations are always allowed, right?
如果導出的對象允許,是的。
c = {}; // but are reassignment allowed too?
不, c
是只讀的。
在評論中,您曾說過:
但是當不再有實時綁定時,將這些變量設為只讀是沒有意義的
記住它們不是變量是有用的,它們是綁定。 雖然變量是一種綁定,但並非所有綁定都是變量(即使在 ES5 及更早版本中)。
關於它們在無關緊要的情況下是只讀的,請記住,涉及兩層綁定:
為了在 #1 中的值不會改變時使 #2 可寫,導入機制必須知道這一點,但該信息不在模塊的 exports 中。 導出只給出導出綁定的名稱。
此外,具有可變導入綁定和不可變導入綁定更難理解,更難實現。 (從樣式的角度來看,重新分配導入的綁定也是令人困惑的。)
同樣重要的是要記住,它們是實時綁定的事實意味着導入的值可能會改變。 假設:
mod1.js
:
export let foo = 41;
export function incrementFoo() {
++foo;
};
mod2.js
:
import { foo, incrementFoo } from "./mod1.js";
console.log(foo); // 41
incrementFoo();
console.log(foo); // 42 <== it changed
在這種特殊情況下,是mod2.js
中的代碼導致了更改(通過調用incrementFoo
),但並非必須如此。 可能是因為在mod1.js
發生了一些與時間相關的事件來改變值,或者其他模塊調用mod1.js
等。
但由於mod2.js
的foo
是一個活生生的結合mod1.js
的foo
, mod2.js
看到的變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.