星空网 > 软件开发 > Java

JavaScript 高级程序设计(第3版)笔记——chapter3:基本概念(函数部分)

3.7函数

3.7.1 理解参数

  • ECMAScript 函数不介意传递进来多个参数,也不在乎传递进来的参数是什么数据类型。因为在 ECMAScript 中的参数在内部是用一个数组来表示的。在函数体内可以通过arguments对象来访问这个参数数组,从而获取传递给函数的每一个参数。
  • 命名的参数只提供便利,但不是必需的。
  • arguments 对象可以与命名参数一起使用。
  • arguments对象的值永远与对应命名参数的值保持同步。不过,这并不是说读取这两个值会访问相同的内存空间。它们的内存空间是独立的,但它们的值会同步。
  • arguments对象的长度有传入的参数的个数决定,不是由定义函数时的命名参数的个数决定的。没有传递值的命名参数将自动被赋予undefined值。
  • ECMAScript 中所有的参数传递的都是值,不可能通过引用传递参数。

arguments对象与命名参数的关系:

 1 function say_hello(var1, var2, var3) { 2   var len = arguments.length; 3    alert(len); 4   for (i in arguments) { 5      alert(arguments[i]); 6    } 7    alert(var1); 8    alert(var2); 9    alert(var3);10 }11 12 say_hello(); //0, undefined, undefined, undefined13 say_hello("first"); // 1, first, first, undefined, undefined14 say_hello("first", "second", "third"); // 3, first, second, third, first, second, third15 say_hello("first", "second", "third", "forth");// 4, first, second, third, forth, first, second, third

1 function say_hello(var1, var2, var3) {2   for (i in arguments) {3     arguments[i] = "change";4    }5   alert(var1 + var2 + var3);6 }7 8 say_hello(1,2,3); //changechangechange

 

3.7.2 没有重载

  • 没有函数签名,真正的重载是不可以做到的。
  • 如果在ECMAScript中定义了两个名字相同的函数,则该名字只属于后定义的函数。
  • 通过检查传入函数中参数的类型和数量并作出不同的反应,可以模拟方法的重载。

没有重载

1 function overLoad (var1) {2   alert("This is the first function");3 }4 5 function overLoad(var1, var2) {6   alert("This is the second function");7 }8 9 overLoad(1); //This is the second function

 

模拟重载

 1 function overLoad () { 2   if (arguments.length === 0) { 3     alert("first"); 4   } else if (arguments.length === 1) { 5     alert("second"); 6   } else { 7     alert("third"); 8   } 9 }10 11 overLoad(); //first12 overLoad(1); //second13 overLoad(1,2,3,4); //third

 




原标题:JavaScript 高级程序设计(第3版)笔记——chapter3:基本概念(函数部分)

关键词:JavaScript

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

日本fba专线物流:https://www.goluckyvip.com/tag/39952.html
日本FCSL:https://www.goluckyvip.com/tag/39953.html
日本tiktok shop:https://www.goluckyvip.com/tag/39954.html
日本毕业季:https://www.goluckyvip.com/tag/39955.html
日本成人礼:https://www.goluckyvip.com/tag/39956.html
日本船运fba:https://www.goluckyvip.com/tag/39957.html
探讨内地人开设香港账户的可行性 :https://www.kjdsnews.com/a/1836442.html
在古巴做游轮 古巴旅游项目:https://www.vstour.cn/a/363194.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流