javascript example code cannot run -
javascript example code cannot run -
there piece of code of online tutorial
sayhi(1); function sayhi(x); { alert(x); // 1 [].shift.call(arguments); alert(x); // undefined, no x more :/ }
in tutorial says:
array methods modify arguments modify local parameters.
actually, modern ecma-262 5th specification splits arguments local variables. of now, browsers still behave described above. seek examples see.
generally, practice not modify arguments.
but tried run above code, output alert 1 twice instead of 1 , undefined.
http://javascript.info/tutorial/arguments
could please clarify me? thanks
as destroy pointed out, reason got syntax error (the horror is) automatic semicolon insertion couldn't right code correctly , of import add together semicolon explicitly.
but meat of question behavior of x
vs. arguments
pseudo-array:
in loose mode (the default), there link between named arguments , arguments
pseudo-array. here's improve demonstration of link:
class="snippet-code-js lang-js prettyprint-override">function foo(x) { snippet.log(x); // "one" snippet.log(arguments[0]); // "one" x = "two"; snippet.log(x); // "two" snippet.log(arguments[0]); // "two" arguments[0] = "three"; snippet.log(x); // "three" snippet.log(arguments[0]); // "three" } foo("one");
class="snippet-code-html lang-html prettyprint-override"><!-- provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
see how arguments[0]
, x
synonyms of each other.
the tutorial refer seems believe shifting arguments
pseudo-array (removing first entry) create x
undefined
because arguments[0]
undefined
@ point. while reasonable interpretation of link between named x
, arguments
pseudo-array, it's not true on chrome's v8, firefox's spidermonkey, ie11's jscript, or ie8's much older jscript.
in strict mode, link between named arguments , arguments
pseudo-array doesn't exist:
class="snippet-code-js lang-js prettyprint-override">function foo(x) { "use strict"; snippet.log(x); // "one" snippet.log(arguments[0]); // "one" x = "two"; snippet.log(x); // "two" snippet.log(arguments[0]); // "one" again, wasn't changed arguments[0] = "three"; snippet.log(x); // "two" again, wasn't changed snippet.log(arguments[0]); // "three" } foo("one");
class="snippet-code-html lang-html prettyprint-override"><!-- provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
in general, it's best utilize strict mode, , not rely on link in loose mode code.
javascript
Comments
Post a Comment