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 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));
});
精彩评论