zoukankan      html  css  js  c++  java
  • [ES6] Function Params

    1. Default Value of function param:

    The function displayTopicsPreview() raises an error on the very first line when called with no arguments. Let's fix that!

    function displayTopicsPreview( topics ){
      var message = "There are currently " + topics.length;
      _displayPreviewMessage(topics, message);
    }
    
    -----------------
    
    function displayTopicsPreview( topics = [] ){
      let message = "There are currently " + topics.length;
      _displayPreviewMessage(topics, message);
    }

    2. Complete the setPageThread() function signature with the missing named parameters. You can check out the body of the function to help discover what options are expected.

    function setPageThread(name,  ){
      let nameElement = _buildNameElement(name);
      let settings = _parseSettings(popular, expires, activeClass);
    
      _updateThreadElement(nameElement, settings);
    }
    
    -------------------
    
    function setPageThread(name,  {popular, expires, activeClass}){
      let nameElement = _buildNameElement(name);
      let settings = _parseSettings(popular, expires, activeClass);
    
      _updateThreadElement(nameElement, settings);
    }

    3. Let's refactor the loadProfiles() function to use named parameters with default values.

    function loadProfiles(userNames = [], options = {}) {
      let profilesClass = options.profilesClass || ".user-profile";
      let reverseSort   = options.reverseSort   || false;
    
      if (reverseSort) {
        userNames = _reverse(userNames);
      }
    
      _loadProfilesToSideBar(userNames, profilesClass);
    }
    
    ------------------------------
    
    function loadProfiles(userNames = [], {profilesClass, reverseSort} = {}) {
      profilesClass = profilesClass || ".user-profile";
      reverseSort   = reverseSort   || false;
    
      if (reverseSort) {
        userNames = _reverse(userNames);
      }
    
      _loadProfilesToSideBar(userNames, profilesClass);
    }
    function setPageThread(name, {popular, expires, activeClass} = {}){
      // ...
    }
    
    setPageThread("ES2015", {
        popular: true
    }); 
    
    //won't cause error

    Important to take away from here is 

    • Instead of giving options = {} in the function param, we give {profileClass, reserseSort} = {}
    • First it is more clear to see what "options" it is
    • Second we assign default param here.

  • 相关阅读:
    【原创】Javascript-获取URL请求参数
    【原创】Javascript-显示系统时间
    【转载】ASP.NET 生成验证码
    【转载】Word2010编号列表&多级列表
    VirtualBox命令更改虚拟硬盘空间
    查看应用程序或服务端口号
    【原创】设置EXCEL2010打开多个独立窗口
    【原创】Word2010 清除样式
    【原创】打开Excel时提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致"
    【转载】SQL Server XML Path
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5094088.html
Copyright © 2011-2022 走看看