admin管理员组文章数量:1327488
What is the scope of function parameter in Javascript
var greetFunc = function(name){
var something;
}
console.log("Hello" +name);
console.log(something);
I understand the scope of something is just inside the function, it will not exist outside that. But what about name. Why the value is blank for name variable.
What is the scope of function parameter in Javascript
var greetFunc = function(name){
var something;
}
console.log("Hello" +name);
console.log(something);
I understand the scope of something is just inside the function, it will not exist outside that. But what about name. Why the value is blank for name variable.
Share Improve this question asked Jan 25, 2017 at 19:53 SamSam 1892 silver badges10 bronze badges 3- What do you see? What did you expect to see? – Bergi Commented Jan 25, 2017 at 19:58
- Possible duplicate of stackoverflow./questions/30748819/… – DJ. Commented Jan 25, 2017 at 20:01
- Possible duplicate of JavaScript function parameter and scope – DJ. Commented Jan 25, 2017 at 20:01
2 Answers
Reset to default 4Referencing name
outside the function doesn't throw an error like you would expect because it is actually a global variable in every page, part of the global window
object. Typing name
is the same as window.name
.
The something
variable causes an error because it hasn't been defined yet. However, the name variable doesn't cause any problems because it is blank by default, at least in Chrome. You are correct that variables created in a function don't exist outside it.
See https://developer.mozilla/en-US/docs/Web/API/Window/name for details.
The parameter name
is similar to declaring a variable name
at the top of the function.
So the scope of a parameter is the function it is a part of.
本文标签: Function parameter scope in javascriptStack Overflow
版权声明:本文标题:Function parameter scope in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742198484a2431518.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论