2

I'm a bit confused by node.js require system.

I know how to export or module.export function of the required component, but not sure how to enhance js Object with prototype.

For instance, I have a code to enhance js Object with prototype.watch method.

I will have this code in my own npm package, and import with node require.

What is the best manner to do this? Do I need to refactor this code as a function to export and need to execute after require? Thanks.

if (!Object.prototype.watch)
{
    Object.defineProperty(Object.prototype, "watch",
    {
        enumerable: false,
        configurable: true,
        writable: false,
        value: function(prop, handler)
        {
            var
            oldval = this[prop],
                newval = oldval,
                getter = function()
                {
                    return newval;
                },
                setter = function(val)
                {
                    oldval = newval;
                    return newval = handler.call(this, prop, oldval, val);
                };

            if (delete this[prop])
            { // can't watch constants
                Object.defineProperty(this, prop,
                {
                    get: getter,
                    set: setter,
                    enumerable: true,
                    configurable: true
                });
            }
        }
    });
}

// object.unwatch
if (!Object.prototype.unwatch)
{
    Object.defineProperty(Object.prototype, "unwatch",
    {
        enumerable: false,
        configurable: true,
        writable: false,
        value: function(prop)
        {
            var val = this[prop];
            delete this[prop]; // remove accessors
            this[prop] = val;
        }
    });
}
4

1 Answer 1

2

All modules in node.js share the same global scope.

Just require() it and any changes you make to global objects will propagate.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Glad to know as simple as that!
Just keep in mind, if you decide to share your npm package with the world, people won't be happy you're changing global prototypes.
@Matt Greer , thanks, I understand that. So far, it's just for my own project and not in the public repo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.