javascript
深入理解javascript函数参数
arguments
javascript對參數要求很隨意,她才不管你傳進來的參數是什么數據類型,甚至可以不傳參數。實際上,javascript函數調用甚至不檢查傳入形參的個數。
1 function add(x){ 2 return x + 1; 3 } 4 console.log(add(1)); //2 5 console.log(add('1')); // 11 6 console.log(add()); // NAN 7 console.log(add(1,2,5)); //2同名形參
非嚴格模式下函數可以有同名形參,但之鞥呢訪問最后出現的那個。。。
function add(x,x,x,){return x;}console.log(add(2,5,6)); //6參數個數
case1:實參比形參少? 那剩下的形參都設置為undefined
1 function add(x,y){ 2 console.log(x,y) 3 } 4 add(1); // 1,undefined這時候我們可以給y設置一個合理的默認值
1 function add(x,y){ 2 y = y || 10000 3 console.log(x,y); 4 } 5 add(1); //1 10000case2:形參比實參多? 多了就是廢的! 可以通過arguments[i]拿到。
參數再內部是用一個數組表示的,arguments對象并不是Array的實例,它是一個類數組對象。
1 function add(){ 2 console.log(arguments[0],arguments[1],arguments[2]); //1,2,3 3 console.log(arguments[0]+arguments[1]); //3 4 console.log(arguments.length); //4 5 } 6 add(1,2,3,4);case3:形參和實參一樣多? ?此時命名參數和對應arguments對象的值相同,但不是相同的命名空間。換句話說,兩者值同步,命名空間獨立。
?
callee
arguments對象有個callee屬性,是一個指針,指向擁有這個arguments對象的函數,看如下階乘
function factorial(num){if(num <= 1){return 1;}else{return num * factorial(num - 1);}}factorial(6); //720 1 function factorial(num){ 2 if(num <= 1){ 3 return 1 4 }else{ 5 return num * arguments.callee(num -1); 6 } 7 } 8 factorial(6); //720?
caller
函數的caller屬性保存著調用當前函數的函數的應用,如果是在全局作用于中調用當前函數,它的值是null
下面這個沒撒意義,好玩而已
1 function mother(){ 2 son(); 3 } 4 function son(){ 5 mother(); 6 } 7 mother(); //Uncaught RangeError: Maximum call stack size exceeded 8 //棧溢出。。。這個才是正道
1 function mother(){ 2 son() 3 } 4 function son(){ 5 console.log(son.caller); 6 } 7 mother(); //function mother(){son()}arguments對象的caller始終是undefined,這樣定義時為了和函數的caller區分開。。
1 function mother(x){ 2 console.log(arguments.caller); 3 } 4 mother(100); //undefined參數傳遞
case1:基本類型值
1 function addTen(num){ 2 num += 10; 3 return num; 4 } 5 var count = 20; 6 var result = addTen(count); 7 console.log(count);//20,沒有變化 8 console.log(result);//30case2:引用類型值
在向參數傳遞引用類型的值時,會把這個值在內存中的地址復制給一個局部變量,因此這個局部變量的變化會反應在函數的內部(好特么拗口!!)
1 function setInfo(obj){ 2 obj.name = 'lihong' 3 } 4 var person = new Object(); 5 setInfo(person); 6 console.log(person.name); //lihong當在函數內部重寫引用類型的形參時,這個變量引用的就是一個局部對象了。這個局部對象會在函數執行完畢后立即被銷毀
function setInfo(obj){obj.name = 'lihong';console.log(person.name);obj = new Object();obj.name = 'linyao';console.log(person.name);}var person = new Object();運行結果:“老公” “老公” ? 說明了什么? ?婆娘不重要!哈哈
?
轉載于:https://www.cnblogs.com/cdut007/p/7287424.html
總結
以上是生活随笔為你收集整理的深入理解javascript函数参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Optical-Flow光流halcon
- 下一篇: BootStrapJS——modal弹出