• es6this箭头函数


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    </head>
    <body>
    <script>
    var test1=()=>{
    console.log(this.name,this);
    }
    window.name = "obj window";
    class {
    constructor(){
    this.name = "class p";
    }
    func(){
    var test2 = () =>{
    console.log(this.name,this);
    };
    function test3(大专栏  es6this箭头函数 class="params">){
    console.log(this);
    }
    test1();
    test2();//class p
    test3();//undefined
    }
    }
    var p = new P();
    p.func();
    </script>
    </body>
    </html>

    js中函数作用域属于静态作用域,就是函数作用域的嵌套关系在函数定义时确定了,废话不多说直接上例子

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    [javascript] view plain copy
    var a='out a';
    function test(){
    console.log(a); // out a
    }
    function outer(){
    var a="in a";
    test()
    };
    outer();

    ok,接下来就是箭头函数的this,

    以下为我的理解,如有不正之处,望指点。

    箭头函数不能用于构造函数,在上面的例子中,test1箭头函数定义在最外面,当test1函数打印this对象时会根据定义时决定的作用域嵌套关系逐级向上查找,因此查找的是window对象,在test2箭头函数中,由于test2定义在类P的func函数中,test2箭头函数打印this时,会先去func方法查找,找到了,然后打印。test3中,类中的方法默认开启了严格模式 所以test3中this为undefined。 可以将箭头函数中的this类比为函数中定义的变量,使用时按照定义时决定的作用域逐级查找直到找到为止。

    原文地址

  • 相关阅读:
    vscode 远程编辑文件
    neo4j
    sqlite3-python
    pypdf2:下载Americanlife网页生成pdf合并pdf并添加书签
    thisamericanlife 百度api及腾讯翻译-正式版
    为微信二维码添加gif动态背景
    python- www.thisamericanlife.org转pdf
    python爬虫添加请求头
    Python-redis
    k8s权威指南-从xx到oo的实践全接触
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12288776.html
Copyright © 2020-2023  润新知