zoukankan      html  css  js  c++  java
  • Function

    1.function*

    会定义一个生成器函数 (generator function),它返回一个  Generator  对象。

    function* name([param[, param[, ... param]]]) { statements }
    
    • name:函数名
    • param:要传递给函数的一个参数的名称,一个函数最多可以有255个参数。
    • statements:普通JS语句。

    生成器函数在执行时能暂停,后面又能从暂停处继续执行。

    function* idMaker(){
      var index = 0;
      while(index<3)
        yield index++;
    }
    
    var gen = idMaker();
    console.log(gen.next().value); 
    console.log(gen.next().value); 
    console.log(gen.next().value); 
    console.log(gen.next().value); 

    2.箭头函数(arrow function)

    (1).他们比传统函数表达式简洁。

    const arr = [1, 2, 3];
    const squares = arr.map(x => x * x);
    
    // 传统函数表达式:
    const squares = arr.map(function (x) { return x * x });

    (2).箭头函数不会绑定关键字this,我们不需要用bind()或者that = this这种方法了

    function UiComponent() {
        const button = document.getElementById('myButton');
        button.addEventListener('click', () => {
            console.log('CLICK');
            this.handleClick(); // this不再是button
        });
    }

    (3)和this同样没有被箭头函数绑定的参数有

    • arguments
    • super
    • this
    • new.target
    function foo() {
        setTimeout( () => {
            console.log("args:", arguments);
        },100);
    }
    
    foo( 2, 4, 6, 8 );
    // args: [2, 4, 6, 8]

    3.declaration and expression

    在JavaScript中,function declaration 函数声明如下:

    而function expression 函数表达式如下:



    4.scope和closure
    scope:
    在JavaScript中所有的域都是并且只能是被函数域(function scope)所创建,它们不能被for/while循环或者if/switch表达式创建。New function = new scope - 仅此而已。
    一个简单的例子来说明域的创建:

    // Scope A
    var myFunction = function () { 

    // Scope B 
    var myOtherFunction = function () {  
      // Scope C
    };
    };

    创建新的域以及创建本地变量、函数、对象都是如此简单。

    closure:

    闭包就是一个内部函数,它具备访问外部函数变量(这些变量位于作用域链中)的能力[注意变量不包含this和arguments]。

    closure可以干2件事情:

      1)closure可以调用(闭包存储的外部变量是引用而不是值,这点非常重要)在当前函数以外的定义的变量(即使外部函数已经返回);

      2)closure可以修改外部定义的变量值

    function mixFunctionFix(a)
        {
            var result=[],i,n;
            n=a.length;
            for(i=0;i<n;i++){
                //IIFE技术来解决JS缺少块级作用域的解决方案
                (function(j){
                    result[i]=function(){
                        //Closure对外部变量是引用
                        console.log("for j="+j);
                        return a[j];
                    }
                })(i)
            }
            return result;
        }
        var mixcall=mixFunctionFix([10,20,30]);
        var f=mixcall[0];
        console.log(f());//10

  • 相关阅读:
    点击其他地方隐藏div
    jquery获得被选中radio的值
    c++几个新特性
    effective c++ (三)
    80X86保护模式及其编程(一)
    Linux内核完全注释之编程语言和环境(二)
    Linux内核完全注释之编程语言和环境(一)
    linux内核完全注释之微型计算机组成结构
    effective c++ (二)
    effective c++ (一)
  • 原文地址:https://www.cnblogs.com/925039847z/p/9942999.html
Copyright © 2011-2022 走看看