1

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

    }

3 Answers 3

2

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")));

    });
})();
Sign up to request clarification or add additional context in comments.

Comments

0

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"));

});

Comments

0

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));
});

3 Comments

this is the one I am trying to remember.
-1 didn't solve the problem; still exposed something to the global scope
The OP poster didn't say that they trying to avoid binding anything to the global scope, just the function, which this accomplishes.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.