Function becomes undefined when declaring local va

2019-02-20 08:00发布

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

function speakService() {

    var speakService = {};

    var speak = function(word) {
        console.log(word);
    };

    speakService.speak = speak;

    return speakService;
}

Using AngularJS, I want to add this service as dependency:

angular
    .module('login', ['ngRoute'])
    .factory('speakService', [function() {
        var speakService = speakService();
        return speakService;
    }]);

But as soon as the interpreter hits the line:

var speakService = speakService();

the speakService()-function is undefined. If I change the speakService variable to speakSvc like this it works fine:

var speakSvc = speakService();

Can somebody explain why my global function is undefined when declaring a local variable with the same name?

Regards!

3条回答
We Are One
2楼-- · 2019-02-20 08:35

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

查看更多
萌系小妹纸
3楼-- · 2019-02-20 08:53

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.

查看更多
【Aperson】
4楼-- · 2019-02-20 08:54

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;
    }
查看更多
登录 后发表回答