0

EDIT I want the function to be globally accessible

Why does myfunction0 work in the dom ready call and myfunction1 does not work?

external.js file

   (function($) {

    // functions defined like that works
    myfunction0 = function() {
      console.log("hello world");
    }

    // functions defined like that do not work
    function myfunction1() {
      console.log("hello world");
    }

    })(jQuery);

index.html

<script>
$(function () {
  myfunction0(); // works
  myfunction1(); // does not work not defined
})
</script>

Does the first function definition get a global scope whereas the second only a local 'in file' scope?

mahatmanich
  • 10,791
  • 5
  • 63
  • 82

2 Answers2

1

You have not declared the myfunction0 using the var keyword so it has been declared in global scope. function declarations are tied to the scope in which they are declared.

If you add the var keyword to your myfunction0 (as you should) you'll see that neither function will be accessible:

var myfunction0 = function() {
  console.log("hello world");
}

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1
function myfunction1() { }

will be local to the scope in which it's defined. Not the file, but the anonymous function it's wrapped in.

myfunction0 = function() { }

declares a variable (which happens to be a function).

Since there's no var attached, that variable gets global scope.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93