Reputation: 53806
What is the difference between defining a function within document.ready or not ?
Does it affect the scope of when a function can be invoked ?
Example, is there any issues/differences I should be aware of in location definitions of functions inside() & outside() :
<script>
document.ready(){
function inside(){
alert('inside');
}
}
function outside(){
alert('outside');
}
</script>
Upvotes: 0
Views: 305
Reputation: 1242
Javascript has function level scoping, meaning if you define a function in document.ready it won't be available outside document.ready
I would define a namespace outside like so: var app = {};
Then define your inside function like so: app.inside = function() {
Then inside will be available in your app global namespace.
Upvotes: 1
Reputation: 700222
Yes, you can only access the inside
function from inside the callback for the ready
event:
document.ready(function(){
function inside(){
alert('inside');
}
inside(); // works
outside(); // works
});
function outside(){
alert('outside');
}
inside(); // doesn't work
outside(); // works
Upvotes: 2
Reputation: 943207
Does it affect the scope of when a function can be invoked ?
Yes, and nothing else.
(Although your particular example depends on you adding a ready()
method to the document
object first.)
Upvotes: 1