tugberk
tugberk

Reputation: 58444

define a function in JavaScript and not bind it to window object

I want to define a function like below and use it inside Jquery $(document).ready;

function pad2(number) {

     return (number < 10 ? '0' : '') + number

}

I am not sure I am doing it right here. I don't want to bind the function to window object. what kind of way should I follow here to do the following thing right;

    $(function(){

        alert(pad2(eval("10")));

    });

    function pad2(number) {

         return (number < 10 ? '0' : '') + number

    }

Upvotes: 1

Views: 266

Answers (3)

FishBasketGordo
FishBasketGordo

Reputation: 23142

You can make the function a member of another object, like this:

var MyObj = {};

MyObj.pad2 = function pad2(number) {
     return (number < 10 ? '0' : '') + number;
}

$(function(){
    alert(MyObj.pad2(10));
});

Upvotes: 0

Joel Martinez
Joel Martinez

Reputation: 47749

I believe this should work ... you can use self executing functions to control object/function scope.

(function() {
    function pad2(number) {

         return (number < 10 ? '0' : '') + number

    }

    $(function(){

        alert(pad2(eval("10")));

    });
})();

Upvotes: 2

davin
davin

Reputation: 45525

Not sure why you need eval, but yes, your way will indeed create a global, i.e. bind to the window object. Try:

$(function(){

    function pad2(number) {
         return (number < 10 ? '0' : '') + number
    }
    alert(pad2("10"));

});

Upvotes: 0

Related Questions