JavaScript中的"read/write variable"是什么意思?
What does it mean by "read/write variable" in JavaScript?
我正在看书 JavaScript:权威指南。
在第 3.4 节中,它说,
In ECMAScript 3, undefined is a read/write variable, and it can be set
to any value. This error is corrected in ECMAScript 5 and undefined is
read-only in that version of the language.
read/write 变量到底是什么意思?
如果某个东西是 "read/write",这意味着您既可以读也可以写。与只读变量(您不能写入)或只写变量(您不能从中读取;相当不寻常,但完全有可能)形成对比。
在JavaScript中,变量默认为read/write。事实上,直到 ES2015,所有真正的变量都是 read/write。在 ES2018 中,我们得到了 const
,它允许你创建一个只读的 "variable" ("constant"),但它仍然是一个 "variable"(规范称之为 以所有其他方式绑定)。
但是,甚至在 const
之前,通过创建只读 属性 全局对象:
// A global scope, this refers to the global object
Object.defineProperty(this, "answer", {
value: 42,
writable: false // this is the default, including it here for emphasis
});
console.log("answer = ", answer); // 42
answer = 67; // Would be an error in strict mode
console.log("answer = ", answer); // still 42
这是可行的,因为全局对象的属性可以作为全局变量访问。
A read/write 变量表示您可以为其分配一些值并稍后读取相同的变量,例如
var x = 10; writing to it
console.log(x) //prints 10 -- reading from it
直到 ECMAScript 3,"undefined" 是一个 r/w 变量,即你可以做 undefined="foo",这是没有意义的。
我正在看书 JavaScript:权威指南。
在第 3.4 节中,它说,
In ECMAScript 3, undefined is a read/write variable, and it can be set to any value. This error is corrected in ECMAScript 5 and undefined is read-only in that version of the language.
read/write 变量到底是什么意思?
如果某个东西是 "read/write",这意味着您既可以读也可以写。与只读变量(您不能写入)或只写变量(您不能从中读取;相当不寻常,但完全有可能)形成对比。
在JavaScript中,变量默认为read/write。事实上,直到 ES2015,所有真正的变量都是 read/write。在 ES2018 中,我们得到了 const
,它允许你创建一个只读的 "variable" ("constant"),但它仍然是一个 "variable"(规范称之为 以所有其他方式绑定)。
但是,甚至在 const
之前,通过创建只读 属性 全局对象:
// A global scope, this refers to the global object
Object.defineProperty(this, "answer", {
value: 42,
writable: false // this is the default, including it here for emphasis
});
console.log("answer = ", answer); // 42
answer = 67; // Would be an error in strict mode
console.log("answer = ", answer); // still 42
这是可行的,因为全局对象的属性可以作为全局变量访问。
A read/write 变量表示您可以为其分配一些值并稍后读取相同的变量,例如
var x = 10; writing to it
console.log(x) //prints 10 -- reading from it
直到 ECMAScript 3,"undefined" 是一个 r/w 变量,即你可以做 undefined="foo",这是没有意义的。