nic*_*oum 5 javascript global properties this node.js
是否可以在文件范围内添加属性(使用get和set方法)而不使其成为全局文件?(类似于变量声明的方式let或const将如何工作)
这是我到目前为止编写的代码,它可以向全局范围添加属性。
var propertyValue;
Object.defineProperty(global, "PropertyValue", {
get: function () {
return propertyValue;
},
set: function (value) {
propertyValue = value;
}
});
console.log(PropertyValue);
Run Code Online (Sandbox Code Playgroud)
是否可以使该属性仅对声明该文件的文件可见。可以通过声明一个变量并在其中添加所有属性来完成相同的操作。
var fileProperties;
var propertyValue;
Object.defineProperty(fileProperties, "PropertyValue", {
get: function () {
return propertyValue;
},
set: function (value) {
propertyValue = value;
}
});
console.log(fileProperties.PropertyValue);
Run Code Online (Sandbox Code Playgroud)
但是,每次我想要获取/设置属性时,我仍然需要键入该变量的名称。
那么有没有办法创建一个属性
应该在某个对象上访问属性,在 JavaScript 中省略对象的唯一可能是全局属性和with语句。
正如原始代码所示,这将访问全局变量的属性,对本地任务使用全局变量是一种不好的做法,对本地任务使用全局变量是一种不好的做法:
Object.defineProperty(global, "PropertyValue", {...});
console.log(PropertyValue);
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用with语句,该方法已被弃用,并且在严格模式下不起作用:
Object.defineProperty(someObject, "PropertyValue", {...});
with (someObject) {
console.log(PropertyValue);
}
Run Code Online (Sandbox Code Playgroud)
在 Node 中,脚本在模块包装器函数的范围内进行评估,在模块范围内this.PropertyValue引用module.exports.PropertyValue。
可以在导出对象上显式定义属性:
let propertyValue;
Object.defineProperty(exports, "PropertyValue", {
get: function () {
return propertyValue;
},
set: function (value) {
propertyValue = value;
}
});
console.log(exports.PropertyValue);
Run Code Online (Sandbox Code Playgroud)
PropertyValue当此模块被导入时,其他模块将可用。通常没有充分的理由强制封装到让开发人员的生活变得更加困难的地步。如果PropertyValue不打算在模块外部使用,通常使用匈牙利表示法并在内部/私有属性下划线就足够了:
Object.defineProperty(exports, "_PropertyValue", { ... });
Run Code Online (Sandbox Code Playgroud)
这样它仍然可以用于测试。
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |