zoukankan      html  css  js  c++  java
  • es6学习2:es5和es6分别是如何处理函数参数的默认值?

    1.es5和es6分别是如何处理函数参数的默认值?

    es5的写法:

    function f (x,y,z){
        if(y === undefined){
            y=7
        }
        if(z === undefined){
            z=42    
        }
        return(x+y+z)
    }
    console.log(f(1))  //50

    es6的写法,可读性笔记好:默认值可以写在参数上

    function f (x,y=7,z=42){
        
        return(x+y+z)
    }
    console.log(f(1)) //50

     若只改z的默认值,而y不改,这时y的默认值不要写7,而是写undefined就是执行默认值的过程

    function f (x,y=7,z=42){
        return(x+y+z)
    }
    console.log(f(1,undefined,43)) //51

     拓展求参数个数(es6); 注意:es6中不支持用arguments求参数个数

    function f (x,y=7,z=42){
        console.log(f.length) //1,只计算没有默认参数值的参数个数
        return(x+y+z)
    }
    console.log(f(1,undefined,43)) //51

    函数声明写法:

    function hello() {}
    let hello = function(){}

    用箭头函数的写法:

    let hello = () => {}

     箭头函数小括号不能省略,只有当参数只有一个的时候可以省略,如;

    let hello = name => {
         console.log("ada")
    }
    hello() //ada

     那什么时候可以省略函数体的花括号呢?只有返回是表达式就可以,就可以省略return和花括号

    let sum = (x,y,z) => x+y+z
    sum(1,2,3)
    console.log(sum(1,2,3)) //6

    若返回的是一个对象:

    这个花括号跟函数体的花括号不一样,

    let sum = (x,y,z) => ({
         x:x,
         y:y,
         z:z
    })
    console.log(sum(1,2,4)) //{x: 1, y: 2, z: 4}

    这样写也可以,如下:

    let sum = (x, y, z) => {
         return {
               x: x,
               y: y,
               z: z
          }
    }
    console.log(sum(1, 2, 4)) //{x: 1, y: 2, z: 4}

    字符串变量:

    <script>
        function Price(strings,type){
          let s1 = strings[0]
          const retailPrice = 20
          const wholeSalePrice = 16
          let showTxt
          if (type==="retail") {
            showTxt = '购买单价是:'+retailPrice
          }else{
            showTxt = '购买的批发价是:'+wholeSalePrice
          }
          return `${s1}${showTxt}`
        }
        let showTxt = Price`您此次的${'retail'}`
        console.log(showTxt); //您此次的购买单价是:20
        
      </script>

    函数this:

     es5:this是变的

    let test = {
                name:'ada',
                say:function(){
                    console.log(this.name)
                }
            }
            test.say() //ada,是谁调用this就指向谁

    es6:this是不变的

    let demo = {
                name: 'ada',
                say: () => {
                    console.log(this.name, this)
                }
            }
            demo.say() //this指向的是window
  • 相关阅读:
    Python+Selenium自动化篇-3-设置浏览器大小、刷新页面、前进和后退
    Python+Selenium自动化篇-2-定位页面元素的八种方法
    Python+Selenium自动化篇-1-安装模块和浏览器驱动操作方法
    02_Python_数据容器(列表、元祖、集合、字典)
    01_Python_基础知识(变量、字符串、条件控制)
    orm单表操作
    模版导入与继承
    django模板层
    orm视图函数层
    orm路由层
  • 原文地址:https://www.cnblogs.com/huanghuali/p/12550406.html
Copyright © 2011-2022 走看看