将 属性 添加到节点文件

Add a property to a node file

是否可以将 属性(使用 getset 方法)添加到文件范围而不使其成为全局文件? (类似于 letconst 对变量声明的作用)

这是我到目前为止写的代码,它可以向全局范围添加一个属性。

var propertyValue;

Object.defineProperty(global, "PropertyValue", {
    get: function () {
        return propertyValue;
    },
    set: function (value) {
        propertyValue = value;
    }
});

console.log(PropertyValue);

是否可以使 属性 仅对声明它的文件可见。同样的事情可以通过声明一个变量并在其中添加所有属性来完成。

var fileProperties;
var propertyValue;

Object.defineProperty(fileProperties, "PropertyValue", {
    get: function () {
        return propertyValue;
    },
    set: function (value) {
        propertyValue = value;
    }
});

console.log(fileProperties.PropertyValue);

但是每次我想要 get/set a 属性.

时,我仍然需要输入该变量的名称

那么有没有办法创建一个属性

  1. 不完全全局
  2. 无需声明所有者对象即可访问
  3. 可以被eslint识别

回答你所有的问题:

  1. Is not fully global.

  2. Can be accessed without stating the owner object.

  3. Can be recognized by eslint.

是使用constlet语句。

来自 const

的文档

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through reassignment, and it can't be redeclared.

来自 let

的文档

The let statement declares a block scope local variable, optionally initializing it to a value.

如果您希望变量的范围仅限于该文件,请仅使用 this 而不是 global

var propertyValue;

Object.defineProperty(this, "PropertyValue", {
    get: function () {
        return propertyValue;
    },
    set: function (value) {
        propertyValue = value;
    }
});

console.log(this.PropertyValue); // prints undefined

propertyValue={a:1}
console.log(this.PropertyValue) // prints {a:1}

应在某些对象上访问 属性,在 JavaScript 中省略对象的唯一可能性是全局属性和 with 语句。

如原始代码所示,这将访问全局变量上的 属性,对本地任务使用全局变量是一种不好的做法,对本地任务使用全局变量是一种不好的做法:

Object.defineProperty(global, "PropertyValue", {...});

console.log(PropertyValue);

另一种方法是使用 with 语句,该语句已被弃用并且在严格模式下不起作用:

Object.defineProperty(someObject, "PropertyValue", {...});

with (someObject) {
  console.log(PropertyValue);
}

在 Node 中,脚本在 module wrapper function 范围内求值,this.PropertyValue 引用模块范围内的 module.exports.PropertyValue

可以在导出对象上显式定义 属性:

let propertyValue;

Object.defineProperty(exports, "PropertyValue", {
    get: function () {
        return propertyValue;
    },
    set: function (value) {
        propertyValue = value;
    }
});

console.log(exports.PropertyValue);

PropertyValue 将在导入此模块时对其他模块可用。通常没有充分的理由将封装强制执行到开始使开发人员的生活更加艰难的地步。如果 PropertyValue 不打算在模块外使用,通常使用匈牙利符号和下划线 internal/private 属性:

就足够了
Object.defineProperty(exports, "_PropertyValue", { ... });

这样它仍然可以用于测试。