I was reviewing the variable access in the function vs global scope and something new came and surprised me that the following is true: / P>
function foo () {message = 'hi'} warning (message); // References Error: Message Not Defined
This returns an error because foo
has not been called anywhere, but once you do this, It is available globally in space. Got it
Although I clearly read somewhere other than returning works (i.e. using the return keyword) we use them for their side effects (for example, I imagine that inside fu I keep that alert function)
UPDATE I
I am getting a lot of feedback, What should be done again in the global realm by calling the work Areas are? What's going on behind the scenes ...? I think some people might think (as I did) except for the bus, it is in the global realm. In fact, people who do not know, you have to call the function first. Thanks!
return keyword?
No, it depends on specifying a variable that is not declared anywhere. When you do this, in loose mode, it creates a global variable, there is nothing to do with returning the value from the function, and it's nothing you should do & nbsp; & Mdash; Basically, this is a good reason to use a powerful mode and / or a "lint" tool like JSHTT, so that you can find and fix the unseen globe errors.
The function, you ask:
-
to use
< Pre>return
in the function and when, like:function Myfunction () {return "foo"; }
-
Use the result of the function when you call it, eg .:
var variable = myFunction ( ); // or other function (myFunction ()); An example of a specified difference in loose mode and in strict mode to an undeclared variable:
"snippet" data-lang = "js" "Data-hide =" wrong ">function RunLoose () {// in loose mode Try {looseFoo = "bar"; Snippet.log (looseFoo); // "bar"} hold (e) {snippet.log ("found exception:" + e.message); }} Function runStrict () {"strict experiment"; Try it in strict mode {strictFoo = "bar"; // & lt; == References to the reasons snippet.log (strictFoo); } Catch (e) {snippet.log ("found exception:" + e.message); } } run loose(); Runstrict ();
& lt ;! - The script provides `snippet 'object, see http: //meta.stackexchange.com/a/242144/134069 - & gt; & Lt; Script src = "http://tjcrowder.github.io/simple-snippets-console/snippet.js" & gt; & Lt; / Script & gt;
No comments:
Post a Comment