关于#javascript#的问题:为什么用for of就可以打印出内容


<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <button>按钮1</button>
        <button>按钮2</button>
        <script>
            let obj={
                site:"中华人民共和国",
                handleEvent:function(event){
                    console.log(this.site+event.target.innerHTML);
                },
                show:function(){
                    const _this=this;
                    const button=document.querySelectorAll("button");
                    for (const but of button) {
                        but.addEventListener("click",this);
                    }
                }
            }
            obj.show();
        </script>
    </body>
</html>

![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/502626116336175.png "=600 #left")


<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <button>按钮1</button>
        <button>按钮2</button>
        <script>
            let obj={
                site:"中华人民共和国",
                handleEvent:function(event){
                    console.log(this.site+event.target.innerHTML);
                },
                show:function(){
                    const _this=this;
                    const button=document.querySelectorAll("button");
                    button.forEach(function(elem){
                        elem.addEventListener("click",this);
                    })
                }
            }
            obj.show();
        </script>
    </body>
</html>

img


为什么用for of就可以打印出内容,foreach就不行呢?

button.forEach(elem=>{
                        elem.addEventListener("click",this);
                    })

这样就行了,因为你的写法forEach里是个function(elem){......},function中this指向function本身,可以使用箭头函数,箭头函数中的this指向上一级