js中的词法作用域,this和块级作用域

js中的词法作用域,this和块级作用域

箭头函数的this会忽略对象,块级作用域。

{

let a=5;

 let func3=()=>{

console.log('a',this.a)//作用域是在和这个for循环块里面,  5
}

func3();//a undefined

}

以下来自:https://www.cnblogs.com/githubzy/p/5780135.html

当我们将箭头函数直接用于对象的方法时,this的指向就发生了变化:

1

2

3

4

5

6

var obj = {

  age:18,

  getAge: () => this.age

}

console.log(obj.getAge());  //Uncaught TypeError: Cannot read property 'age' of undefined

这是由于目前为止,箭头函数还不能够直接作为对象的方法使用造成的,同理,在类中:

1

2

3

4

5

6

7

8

class obj () {

    constructor (name) {

        this.name = name

    }

    sayName = () => this.name

}

console.log(obj.sayName()); //Uncaught TypeError: obj.sayName is not a function

因此,当我们在使用箭头函数时,需要搞明白我们到底应该用它做什么。建议将一些需要传参并且不作为对象方法使用的函数写作箭头函数会更适合一些。

猜你喜欢

转载自blog.csdn.net/Handsome2013/article/details/114478516