首页 > 其他 > 详细

[ES6] Function Params

时间:2016-01-02 07:00:27      阅读:207      评论:0      收藏:0      [点我收藏+]

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.

[ES6] Function Params

原文:http://www.cnblogs.com/Answer1215/p/5094088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!