This understanding arrows inside the function

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>箭头函数里面的this理解</title>
</head>

<body>
    <script>
        /*
        如何使this.name指向xyz
        */
        const xyz = {
            name: 'xyz',
            hobbies: ['Coding', 'Sleeping', 'Reading'],
            printHobbies:function(){
                console.log(this);//{name: "xyz", hobbies: Array(3), printHobbies: ƒ}
                this.hobbies.map(function(hobby){
                    console.log(this);//this指向window,js是在运行时才绑定的;
                    console.log(`${this.name} love ${hobby}`);
                })
            }
        };
        xyz.printHobbies();

        //ES5
        const xyz1 = {
            name: 'xyz',
            hobbies: ['Coding', 'Sleeping', 'Reading'],
            printHobbies:function(){
                var self=this;
                this.hobbies.map(function(hobby){
                    console.log(`${self.name} love ${hobby}`);
                })
            }
        };
        xyz1.printHobbies();

         //ES6
         /*
         箭头函数没有自己的this值,它的this值是继承父作用域的
         */
         const xyz2 = {
            name: 'xyz',
            hobbies: ['Coding', 'Sleeping', 'Reading'],
            printHobbies:function(){
                this.hobbies.map(hobby=>{
                    console.log(`${this.name} love ${hobby}`);
                })
            }
        };
        xyz2.printHobbies();



    </script>
</body>

</html>

 

Guess you like

Origin blog.csdn.net/JEFF_luyiduan/article/details/91408927