Srle
Srle

Reputation: 10496

Requirejs and avoiding polluting the global scope

I suppose that I don't understand Require.js very well, so I wanted to ask why I can change firstName and lastName like in the example below (globally).

Shouldn't Require.js do stuff about avoiding polluting the global scope? I'm just providing the interface for creating an object, not for changing it's content. Thanks a lot.

// someModule.js
define([], function() {
    function Employee(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;        
    }

    Employee.prototype.getName = function() {
        return this.firstName = ' ' = this.lastName;
    }

    return {
        createEmployee: function(fName, lName) {
            return new Employee(fName, lName);
        };
    };
});

// main.js
require(['jquery', 'someModule'], function($, someModule) {
    $(function() {
        var x = someModule.createEmployee('John', 'Doe');
        document.write(x.getName() + '<br>');
        x.firstName = 'Some other name';
        x.lastName = 'Some other surname';
        document.write(x.getName());
    });
});

And the output is:
John Doe
Some other name Some other surname

Upvotes: 1

Views: 903

Answers (3)

c24w
c24w

Reputation: 7856

I think you're confusing global leaks with visibility of properties. firstName and lastName aren't leaked - they're just publicly accessible and modifiable (mutable). If you want to hide them, you could do something like this:

function Employee(firstName, lastName) {    
    this.getFirstName = function () { return firstName; };
    this.getLastName = function () { return lastName; };
}

Employee.prototype.getName = function () {
     return this.getFirstname() + ' ' + this.getLastName();
};

Upvotes: 2

Pointy
Pointy

Reputation: 413702

Your created objects have properties, "firstName" and "lastName". Your code did nothing to prevent modifications to those properties.

In newer JavaScript implementations, there are ways to do that, but Requirejs isn't going to do it automatically (at least not without a significant redesign or enhancement project).

Specifically, the defineProperty method lets you make read-only properties. Now, that will prevent all code from modifying the properties. If you want properties that are under control of the object, you can use a technique like what @c24w suggests in another answer.

Upvotes: 1

Adidi
Adidi

Reputation: 5253

you don't polute any global scope here - your code runs inside anonymous function (closure) and nothing is bind to the window global object - so it's fine.

Upvotes: 1

Related Questions