一白山中

自分を磨き、自分なりの幸せを追求しよう

JavaScript関数

後で定義される関数は、前のを覆す

function
test() { console.log("test"); } test(); // "test arg0 + undefined" 出力 function test(arg1) { console.log("test arg" + arguments.length + " + " + arg1); } test(1,2); // "test arg2 + 1" 出力

足りない引数は、undefinedになる
多めの引数は、argumentsで取り出す可能である

function
test(arg1) { for(var i=0; i<arguments.length; i++) { console.log(arguments[i]); } } test(1,2); // 1 2 出力
変数と関数が重複する際には、変数が勝ち

var
a = 100; function a() { return "function"; } console.log(a); // 100 出力 console.log(a()); /* エラー Uncaught TypeError: a is not a function (anonymous function) @test.html:9 */

匿名関数

var
a = 100; var a = function() { return "function"; } console.log(a); /* function() { return "function"; }
出力 */
console.log(a()); // "function" 出力

関数とそのうちの変数と重複する場合

function
a() { console.log(this); // window{...} 出力 this.a = 1; //いわゆる window.a = 1,この時のwindowもとのfunction aが変数で覆される var a = 5; //下記の変数は全部{}範囲内で有効である a = 10; var v = "value" return "function"; } console.log(a); // function a {...} 出力 console.log(a()); // "function" 出力 console.log(a); // 1 出力 console.log(v); /* Uncaught ReferenceError: v is not defined (anonymous function) @ mycolor.html:15 */
出力