Function becomes undefined when declaring local variable with same name

前端 未结 3 755
甜味超标
甜味超标 2021-01-16 12:45

I have declared a function in file so that it becomes global:

相关标签:
3条回答
  • 2021-01-16 13:12

    It's because of javascript's hoisting

    function() {
            var speakService = speakService();
            return speakService;
        }
    

    Will be same as

    function() {
            var speakService; //Declaration moved to top
            speakService = speakService(); //here speakService is undefined
            return speakService;
        }
    
    0 讨论(0)
  • 2021-01-16 13:21

    The reason why the variable appears to be undefined is hoisting. When you write something like var x = 3 the definition of x is hoisted to the top of the current scope (functional in this case since you are using var). The assignment itself happens when you hit that particular line.

    So in your specific case, when you enter the scope of that variable you define it var speakService first, which hides the function speakService from the rest of the scope. Then you try to execute the line speakService = speakService() and since speakService is just an uninitialized variable you get undefined.

    0 讨论(0)
  • 2021-01-16 13:34

    Like others have said, your issue is hoisting. Just return an object literal and use the IIFE pattern.

    var myService = (function speakService() {
        var speak = function(word) {
            console.log(word);
        };
      
        return {
          speak: speak
        };
    })();
    
    myService.speak("TEST");

    0 讨论(0)
提交回复
热议问题