window.onload = function() { // console.log('ok'); //正規的創建函數 function test(abc, d) { return abc(d); } function jack(testString) { console.log(testStri... ...
window.onload = function() { // console.log('ok'); //正規的創建函數 function test(abc, d) { return abc(d); } function jack(testString) { console.log(testString); } test(jack, 'jackjones'); test(jack, '我是Jack,您好!'); //通過Function()創建函數 var b = new Function('x,y', 'return x+y'); console.log(b(5, 2)); //創建匿名函數 var c = function() { console.log('我是您名函數!請問你是麽?'); } c(); //調用匿名函數 var d = null; if(7 > 8) { d = function() { console.log('7>8'); } } else { d = function() { console.log('7<8'); } } // console.log(d); d(); function testfor() { for(var i = 0; i < arguments.length; i++) { console.log(i); } for(var i = 0; i < 5; i++) { console.log(i); } } testfor(1, 2, 3, 4, 5, 6, 7, 8); console.log('======================='); //普通的遞歸函數的寫法 function digui(num) { if(num == 1) { return 1; } else { return num * digui(num - 1); } } console.log(digui(4)); //調用遞歸函數 //使用arguments.calle方法實現遞歸方法 function digui_num(num) { if(num == 1) { return 1; } else { return num * arguments.callee(num - 1); } } var OtherDIgui = digui_num; digui = null; console.log(OtherDIgui(4)); //this的使用方法 color = 'yellow' function TestColor() { var color = 'red'; console.log(this.color); //這裡的this指向的是window對象 } function TestColor_Test1() { var color = 'red'; console.log(color); //這裡沒有加this表示從函數裡面網外面找 } function TestColor_Test2() { var color = 'black'; function test2() { var color = 'test2color'; function test1() { var color = 'test1color'; return color; } return test1(); } return color; } TestColor(); TestColor_Test1(); console.log('=========================='); TestColor_Test2(); //閉包的使用方法研究 function bibao() { var fontsize = '微軟雅黑'; return function bibao1() { var fontsize = '行書'; return fontsize; } } function bibao1() { var jack = 'jack'; return function() { console.log(jack); } } //調用閉包的匿名函數 var p = bibao1(); p(); //調用非匿名函數的內部函數 console.log(bibao()()); function bibao2() { var n = 100; function fn() { return n; } return fn; //將函數的指針作為函數返回 } console.log(bibao2()()); console.log('-========') //閉包實現累加功能 function fn1() { var n = 1; add = function() { n += 1; } function fn2() { n += 1; console.log(n); } return fn2; } var resule = fn1(); resule(); resule(); resule(); resule(); resule(); //研究JavaScript閉包中的this含義 var obj = { testname: 'jack', fun: function() { var testname = 'funTest'; console.log(this.testname); //此處訪問到的name為obj的值 return function InnerFun() { console.log(this.testname); //此處的testname的值為Window的值,所以列印出來為undeifined }; }, addr: '上海市徐匯區', fn: function() { var age = 100; var t = this; return function() { console.log(t.testname); //將this進行轉換 } } } var pp = obj.fun(); console.log(obj.addr); pp(); //undefined var b = obj.fn(); b(); //jack //創建匿名函數 var n = function() { console.log('ok'); } n(); //匿名函數的調用 //創建自動執行的函數 (function() { console.log('我是自動執行函數'); })(); //使用function創建函數 var f = new Function('x,y', 'console.log(x*y)'); f(10, 10); }