声明具有相同名称的局部变量时

声明具有相同名称的局部变量时

本文介绍了声明具有相同名称的局部变量时,函数变得不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在文件中声明了一个函数,以便使其成为全局函数:

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;
}

使用AngularJS,我想将此服务添加为依赖项:

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

speakService()函数未定义.如果我像这样将speakService变量更改为speakSvc,则效果很好:

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?

致谢!

推荐答案

变量似乎未定义的原因是吊装.当您编写类似 var x = 3 之类的内容时, x 的定义将被提升到当前作用域的顶部(在这种情况下,此功能可以使用,因为您使用的是 var ).当您点击该特定行时,作业本身就会发生.

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.

因此,在您的特定情况下,当您输入该变量的范围时,首先要定义它 varpeakService ,这会将函数 speakService 隐藏在其余范围内.然后,您尝试执行 speakService = talkService()行,由于 speakService 只是一个未初始化的变量,因此无法定义.

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.

这篇关于声明具有相同名称的局部变量时,函数变得不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:21