js,this关键字

66 阅读1分钟
       => this表示当前对象
       => 在同场景下this表示不同的对象

事件处理函数中的this

this->事件源

  <button>确定</button>
   <body>
    <button>确定</button>
    <script>
        var btn = document.querySelector('button')
        btn.addEventListener('click', function () {
            // this->事件源->button按钮
            console.log('this:', this)
        })
    </script>
</body>

普通函数/定时器/自调用函数中的this

       1. 普通函数中this
            this -> window对象
       2. 定时器中this
            this -> window对象
       3. 自调用函数中this
            this -> window对象

1

this ->  Window
 <script>
      function fun(){
                console.log('this -> ',this)
            }
            fun()
 </script>

2

       this ->  Window
       setTimeout(function(){
       console.log('定时器 this -> ',this)
       },1000)

3

             this ->  Window
             (function(){
                 console.log('自调用函数this -> ',this)
             })()

对象方法中的this

调用该方法引用变量(obj)指向的对象(堆区里面的内容)
内存分为堆区与栈区,引用变量obj存储在栈区,真正的对象存在堆区里
 var obj = {
                name:'jack',
                say: function(){
                    //调用当前对象属性
                   console.log(this.name + '说话, say方法调用');
                   console.log('对象Object方法中this -> ',this)
                }
            }

            obj.say()