微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以将 module.exports 设置为 setter/getter javascript?

如何解决是否可以将 module.exports 设置为 setter/getter javascript?

文件 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)

解决方法

是的!但也没有。

虽然这在技术上是可行的,但您会遇到无法访问 setter 的问题,因为它会在 require() 调用时调用 Getter 并返回值。所以 getter/setter 功能只能通过源文件访问,getter 提供对 require 的响应。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。