zoukankan      html  css  js  c++  java
  • ES6-Function

    Function

    箭头函数

    • ES6中对于函数的扩展最吸引人的莫过于箭头函数啦,不多说,先学会再说。
    • 函数体内的this对象,是定义时所在的对象,而不是使用时所在的对象,这个特性与正常函数不同。
    // 箭头定义函数
    function foo() {
      setTimeout(() => {
        console.log('id:', this.id); // this指向{id:42}这个对象
      }, 100);
    }
    var id = 21;
    foo.call({ id: 42 }); // 42
    
    // 普通定义函数
    function foo() {
      setTimeout(function(){
        console.log('id:', this.id); // this指向window
      }, 100);
    }
    var id = 21;
    foo.call({ id: 42 }); // 21
    
    • 不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。没有内部this。不过都ES6了,想要定义类,直接使用class不就得了
    var Demo = (foo) => console.log(foo);
    new Demo('foo') // 报错啦 testFunc is not a constructor
    
    • 不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数(...args)代替。
    var demo = (foo) => console.log(arguments);
    demo() // 报错 arguments is not defined
    
    // 可以用Rest写法代替
    var demo = (...args) => console.log(args);
    demo('a') // ["a"]
    
    • 不可以使用yield命令,因此箭头函数不能用作Generator函数。待研究^^!!

    参数默认值

    • 尾参数设置默认值
    let log = (x, y = 'World') => x + ' ' + y;
    log('hello', 'xiaoming'); // hello xiaoming
    log('hello'); // hello World
    

    参数解构赋值

    函数的length属性

    • 返回未设置默认值的参数的个数
    ((x, y, z = 1) => 1).length // 2
    
    • 如果设置默认值的参数不是尾参数,设置默认值的参数后面的未设置默认值的参数也不计入length
    ((x = 1, y, z) => 1).length // 0
    

    作用域

    var x = 1;
    function foo(x, y = x){
        console.log(y);
    }
    foo(2) // 2
    
    let x = 1;
    function foo(y = x){
        let x = 2;
        console.log(y);
    }
    foo() // 1
    

    rest参数

    • rest参数后面不能再有参数
    (a, ...b) => 1
    (a, ...b, c) => 1 // 报错
    
  • 相关阅读:
    好用的PasswordTextBox.
    可以修改Autocomplete高度和宽度的TextBox.(ComboBox也试用)
    Show WER and DMP file information
    在webBrowser中触发html页面中的javaScript.
    Trigger in sql server
    黑客来了。。。键盘钩子,听起来很高端。
    Send email
    (VB.net)自定义TableLayoutPanel使它能够在运行时用鼠标改变行高和列宽。
    (C#) Format the cell of DataGridView based on the TextBox.Text
    可以用来测显示屏的inch数。
  • 原文地址:https://www.cnblogs.com/ddfe/p/5609687.html
Copyright © 2011-2022 走看看