在全局作用域中

=>this -> window

  1. <script>
  2. console.log(this); //this->window
  3. </script>

在普通函数中

=>this取决于谁调用,谁调用我,this就指向谁,跟如何定义无关

  1. var obj = {
  2. fn1:function() {
  3. console.log(this);
  4. },
  5. fn2:function(){
  6. fn3()
  7. }
  8. }
  9. function fn3() {
  10. console.log(this);
  11. }
  12. fn3();//this->window
  13. obj.fn1();//this->obj
  14. obj.fn2();//this->window

image.png

箭头函数中的this

箭头函数没有自己的this,箭头函数的this就是上下文中定义的this,因为箭头函数没有自己的this所以不能用做构造函数。

  1. var div = document.querySelector('div');
  2. var o={
  3. a:function(){
  4. var arr=[1];
  5. //就是定义所在对象中的this
  6. //这里的this—>o
  7. arr.forEach(item=>{
  8. //所以this -> o
  9. console.log(this);
  10. })
  11. },
  12. //这里的this指向window o是定义在window中的对象
  13. b:()=>{
  14. console.log(this);
  15. },
  16. c:function() {
  17. console.log(this);
  18. }
  19. }
  20. div.addEventListener('click',item=>{
  21. console.log(this);//this->window 这里的this就是定义上文window环境中的this
  22. });
  23. o.a(); //this->o
  24. o.b();//this->window
  25. o.c();//this->o 普通函数谁调用就指向谁

事件绑定中的this

事件源.onclik = function(){ } //this -> 事件源
事件源.addEventListener(function(){ }) //this->事件源

  1. var div = document.querySelector('div');
  2. div.addEventListener('click',function() {
  3. console.log(this); //this->div
  4. });
  5. div.onclick = function() {
  6. console.log(this) //this->div
  7. }

定时器中的this

定时器中的this->window,因为定时器中采用回调函数作为处理函数,而回调函数的this->window

  1. setInterval(function() {
  2. console.log(this); //this->window
  3. },500)
  4. setTimeout(function() {
  5. console.log(this); //this->window
  6. },500)

构造函数中的this

构造函数配合new使用, 而new关键字会将构造函数中的this指向实例化对象,所以构造函数中的this->实例化对象
new关键字会在内部发生什么

  1. //第一行,创建一个空对象obj。
  2. var obj ={};
  3. //第二行,将这个空对象的__proto__成员指向了构造函数对象的prototype成员对象.
  4. obj.__proto__ = CO.prototype;
  5. //第三行,将构造函数的作用域赋给新对象,因此CA函数中的this指向新对象obj,然后再调用CO函数。于是我们就给obj对象赋值了一个成员变量p,这个成员变量的值是” I’min constructed object”。
  6. CO.call(obj);
  7. //第四行,返回新对象obj。
  8. return obj;
  1. function Person(name,age) {
  2. this.name = name;
  3. this.age = age;
  4. }
  5. var person1 = new Person();
  6. person1.name = 'andy';
  7. person1.age = 18;
  8. console.log(person1);//Person {name: "andy", age: 18}
  9. var person2 = new Person();
  10. person2.name = 'huni';
  11. person2.age = 20;
  12. console.log(person2);// Person {name: "huni", age: 20

博客——js中this理解