javascript
深入理解javascript函数参数
arguments
javascript對參數(shù)要求很隨意,她才不管你傳進(jìn)來的參數(shù)是什么數(shù)據(jù)類型,甚至可以不傳參數(shù)。實際上,javascript函數(shù)調(diào)用甚至不檢查傳入形參的個數(shù)。
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同名形參
非嚴(yán)格模式下函數(shù)可以有同名形參,但之鞥呢訪問最后出現(xiàn)的那個。。。
function add(x,x,x,){return x;}console.log(add(2,5,6)); //6參數(shù)個數(shù)
case1:實參比形參少? 那剩下的形參都設(shè)置為undefined
1 function add(x,y){ 2 console.log(x,y) 3 } 4 add(1); // 1,undefined這時候我們可以給y設(shè)置一個合理的默認(rèn)值
1 function add(x,y){ 2 y = y || 10000 3 console.log(x,y); 4 } 5 add(1); //1 10000case2:形參比實參多? 多了就是廢的! 可以通過arguments[i]拿到。
參數(shù)再內(nèi)部是用一個數(shù)組表示的,arguments對象并不是Array的實例,它是一個類數(shù)組對象。
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:形參和實參一樣多? ?此時命名參數(shù)和對應(yīng)arguments對象的值相同,但不是相同的命名空間。換句話說,兩者值同步,命名空間獨立。
?
callee
arguments對象有個callee屬性,是一個指針,指向擁有這個arguments對象的函數(shù),看如下階乘
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
函數(shù)的caller屬性保存著調(diào)用當(dāng)前函數(shù)的函數(shù)的應(yīng)用,如果是在全局作用于中調(diào)用當(dāng)前函數(shù),它的值是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,這樣定義時為了和函數(shù)的caller區(qū)分開。。
1 function mother(x){ 2 console.log(arguments.caller); 3 } 4 mother(100); //undefined參數(shù)傳遞
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:引用類型值
在向參數(shù)傳遞引用類型的值時,會把這個值在內(nèi)存中的地址復(fù)制給一個局部變量,因此這個局部變量的變化會反應(yīng)在函數(shù)的內(nèi)部(好特么拗口!!)
1 function setInfo(obj){ 2 obj.name = 'lihong' 3 } 4 var person = new Object(); 5 setInfo(person); 6 console.log(person.name); //lihong當(dāng)在函數(shù)內(nèi)部重寫引用類型的形參時,這個變量引用的就是一個局部對象了。這個局部對象會在函數(shù)執(zhí)行完畢后立即被銷毀
function setInfo(obj){obj.name = 'lihong';console.log(person.name);obj = new Object();obj.name = 'linyao';console.log(person.name);}var person = new Object();運行結(jié)果:“老公” “老公” ? 說明了什么? ?婆娘不重要!哈哈
?
轉(zhuǎn)載于:https://www.cnblogs.com/cdut007/p/7287424.html
總結(jié)
以上是生活随笔為你收集整理的深入理解javascript函数参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Optical-Flow光流halcon
- 下一篇: winload.exe数字签名问题详解