探究函数内部的this指向问题

tech2022-10-12  112

函数内部的this指向

这些 this 的指向,是当我们调用函数的时候确定的。调用方式的不同决定了this 的指向不同 一般指向我们的调用者.

调用方式this指向普通函数调用window构造函数调用实例对象 原型对象里面的方法页指向实例对象对象方法调用该方法所属对象事件绑定方法绑定事件对象定时器函数window立即执行函数window <button>点击</button> <script> // 函数的不同调用方式决定了this 的指向不同 // 1. 普通函数 this 指向window function fn() { console.log('普通函数的this' + this); } window.fn(); //普通函数的this[object Window] // 2. 对象的方法 this指向的是对象 o var o = { sayHi: function() { console.log('对象方法的this:' + this); } } o.sayHi(); // 对象方法的this:[object Object] // 3. 构造函数 this 指向 ldh 这个实例对象 原型对象里面的this 指向的也是 ldh这个实例对象 function Star() {}; Star.prototype.sing = function() { console.log('构造函数'+this); } var ldh = new Star(); ldh.sing(); // 构造函数[object Object] // 4. 绑定事件函数 this 指向的是函数的调用者 btn这个按钮对象 var btn = document.querySelector('button'); btn.onclick = function() { console.log('绑定时间函数的this:' + this); }; // 绑定时间函数的this:[object HTMLButtonElement] // 5. 定时器函数 this 指向的也是window window.setTimeout(function() { console.log('定时器的this:' + this); }, 1000); //定时器的this:[object Window] // 6. 立即执行函数 this还是指向window (function() { console.log('立即执行函数的this' + this); })(); // 立即执行函数的this[object Window] </script> //7.箭头函数 //1)箭头函数中的this是通过继承得到的,可以理解成其本身并没有this,是通过谁调用(其父对象来判断的,谁调用它谁就是this) //2) 如果箭头函数的直接上层作用域拥有this,则使用之;如果没有,则沿着其作用域链继续向上查找 //3)箭头函数中使用的this指向其被定义时所在的作用域;普通函数中使用的this指向运行时所在的作用域 <script type="text/javascript"> var age = 100; var obj = { age: 20, say: () => { console.log(this.age); } } obj.say(); // 输出 100 //箭头函数this指向的是被声明的作用域里面,而对象没有作用域的,所以箭头函数虽然在对象中被定义,但是this指向的是全局作用域 </script>
最新回复(0)