简体   繁体   English

为什么这个变量在我执行“函数MyVar(){}”之前有一个值?

[英]Why does this variable have a value before I do “function MyVar() {}”?

I'm trying to understand why this code behaves the way it does: 我试图理解为什么这段代码的行为方式如下:

test.js test.js

var User;

console.dir(User);

function User(name) { // User = function(name) { ... seems not to be the same?
    this.name = name;
}

node test.js node test.js

[Function: User]

Why does User have a value before the function() statement? 为什么Userfunction()语句之前有值?

Hoisting! 起重! http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

var and function statements are automatically hoisted to the top of the script! varfunction语句自动提升到脚本的顶部!

This allows functions to be used before they are defined, like this: 这允许函数在定义之前使用,如下所示:

dothis();
function dothis() { alert('wow'); }

edit function statements like this are not affected: 这样的编辑 function语句不受影响:

myfunc(); // won't work
var myfunc = function() { alert('nope'); }

That function is defined at parse time. 该函数在解析时定义。

Please refer to: var functionName = function() {} vs function functionName() {} 请参考: var functionName = function(){} vs function functionName(){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM