Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a property to a node file

Tags:

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

  1. Is not fully global
  2. Can be accessed without stating the owner object
  3. Can be recognized by eslint
like image 267
nick zoum Avatar asked Jun 17 '18 18:06

nick zoum


1 Answers

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.

like image 65
Estus Flask Avatar answered Sep 23 '22 00:09

Estus Flask