Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The way of good scoping in JavaScript

I am not a really good JavaScript user but I can get things done with it. I am not proud of the code I have written in JavaScript, so I decided to change that. Here is my first step:

I am trying create my own library for a project and the below is the initial structure.

window.fooLib = {};

(function (foo) {
    "use strict";

    foo.doSomeStuff = function(param1) { 

        console.log(new AccommProperty(param1));
    }

    //some internal function
    function AccommProperty(nameValue) { 
        var _self = this;
        _self.name = nameValue;
    }

}(fooLib));

I used immediately invoked function expression here to initialize my variable. In this case it is fooLib.

I am not sure if I should do some other things to make window.fooLib more safe. I mean it can be overridden by any other code which will run after my code if I understand JavaScript correctly.

What are your thoughts?

like image 648
tugberk Avatar asked Mar 19 '12 08:03

tugberk


1 Answers

If you want to prevent overwriting your variables, you may use Object.defineProperty() with writable:false, configurable:false. In your case:

(function () {
    "use strict";
    var foo = {};
    //some internal function
    function AccommProperty(nameValue) { 
        var _self = this;
        _self.name = nameValue;
    }
    foo.doSomeStuff = function(param1) { 

        console.log(new AccommProperty(param1));
    }
    Object.defineProperty(window, "foolib", {value:foo});
}());

Still, there is no good reason for that. It would need EcamScript 5.1 to work, and there are no shims around; maybe something with getters/setters to prevent overwriting with the = operator.

But also, there should be no need to make your library un-overwritable. Just don't use code on your site that overrides the lib. Or maybe someone even wants to overwrite your functions with another, better lib with the same interface?

If the question is about a library to be shared, with possible namespace conflicts to others, you may have a look at jQuery.noConflict.

like image 86
Bergi Avatar answered Oct 13 '22 12:10

Bergi