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); }; console.log(this); } test1(); test2(); test3(); } } 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); } 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类比为函数中定义的变量,使用时按照定义时决定的作用域逐级查找直到找到为止。
原文地址