【发布时间】:2021-06-06 02:10:47
【问题描述】:
在文件 a.js 中
// a.js
let a = 1
Object.defineProperty(module, "exports", {
get() {
return a
},
set(v) {
a += 1
},
enumerable: true,
configurable: true,
})
在文件 b.js 中
// b.js
const a = require("./a")
console.log(a) // 1
a = 2 // a should now be 3
// Throws "Uncaught TypeError: Assignment to constant variable."
有没有办法做到这一点? (在我require'd 上使用 setter)
【问题讨论】:
-
这里稍微解释一下发生了什么。当您需要 a 时,您将获得 getter 返回的值,而不是 getter 对象本身,因为它是 getter,因此返回的对象是数字,而不是对象。您还将值分配给一个不能被覆盖的常量。
标签: javascript node.js getter-setter accessor