Is it possible to add a property (with get
and set
method) to the scope of a file without making it global? (Similar to how let
or const
would work for a variable declaration)
This is the code I've written so far, It can add a property to the global scope.
var propertyValue;
Object.defineProperty(global, "PropertyValue", {
get: function () {
return propertyValue;
},
set: function (value) {
propertyValue = value;
}
});
console.log(PropertyValue);
Is it possible to make the property only visible to just the file it was declared in. The same thing can be done by declaring a variable and adding all properties there.
var fileProperties;
var propertyValue;
Object.defineProperty(fileProperties, "PropertyValue", {
get: function () {
return propertyValue;
},
set: function (value) {
propertyValue = value;
}
});
console.log(fileProperties.PropertyValue);
But then I still need to type the name of that variable every time I want to get/set a property.
So is there a way to create a property that
A property should be accessed on some object, the only possibilities for an object to be omitted in JavaScript are global properties and with
statement.
As the original code shows, this will access a property on global variable, using global variables for local tasks is a bad practice, Using global variables for local tasks is a bad practice:
Object.defineProperty(global, "PropertyValue", {...});
console.log(PropertyValue);
Another way is to use with
statement, which is deprecated and won't work in strict mode:
Object.defineProperty(someObject, "PropertyValue", {...});
with (someObject) {
console.log(PropertyValue);
}
In Node, a script is evaluated in the scope of module wrapper function, this.PropertyValue
refers to module.exports.PropertyValue
in module scope.
A property can be defined on export object explicitly:
let propertyValue;
Object.defineProperty(exports, "PropertyValue", {
get: function () {
return propertyValue;
},
set: function (value) {
propertyValue = value;
}
});
console.log(exports.PropertyValue);
PropertyValue
will be available to other modules when this module is imported. There are usually no good reasons to enforce encapsulation to the point where it starts to make developer's life harder. If PropertyValue
isn't intended to be used outside the module, usually it's enough to use Hungarian notation and underscore internal/private property:
Object.defineProperty(exports, "_PropertyValue", { ... });
This way it's still available for testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With