zoukankan      html  css  js  c++  java
  • JavaScript 高级程序设计(第3版)笔记——chapter3:基本概念(函数部分)

    3.7函数

    3.7.1 理解参数

    • ECMAScript 函数不介意传递进来多个参数,也不在乎传递进来的参数是什么数据类型。因为在 ECMAScript 中的参数在内部是用一个数组来表示的。在函数体内可以通过arguments对象来访问这个参数数组,从而获取传递给函数的每一个参数。
    • 命名的参数只提供便利,但不是必需的。
    • 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, undefined
    13 say_hello("first"); // 1, first, first, undefined, undefined
    14 say_hello("first", "second", "third"); // 3, first, second, third, first, second, third
    15 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(); //first
    12 overLoad(1); //second
    13 overLoad(1,2,3,4); //third
  • 相关阅读:
    《ODAY安全:软件漏洞分析技术》学习心得-----shellcode的一点小小的思考
    关于《加密与解密》的读后感----对dump脱壳的一点思考
    React-Native(四):React Native之View学习
    React-Native(二):React Native开发工具vs code配置
    SqlServer优化:当数据量查询不是特别多,但数据库服务器的CPU资源一直100%时,如何优化?
    React-Native(一):React Native环境搭建
    游戏资源收集
    Java-NIO(九):管道 (Pipe)
    Java-NIO(八):DatagramChannel
    Java-NIO(七):阻塞IO与非阻塞IO
  • 原文地址:https://www.cnblogs.com/HiuYanChong/p/5285270.html
Copyright © 2011-2022 走看看