开发者

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

开发者 https://www.devze.com 2023-03-15 10:20 出处:网络
I want to define a function like below and use it inside Jquery $(document).ready; function pad2(number) {

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 bi开发者_开发百科nd 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

    }


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

    });
})();


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

});


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号