this指向问题

时间:2020-11-30
本文章向大家介绍this指向问题,主要包括this指向问题使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

经常在代码中使用this,但是没有总结过this指向的问题。

  var name = "Jake";
  function testThis() {
    this.name = 'jakezhang';
    this.sayName = function () {
      return this.name;
    }
  }
console.log('第一个this===', this); // this指向window console.log(this.name); // Jake new testThis(); console.log('第二个this', this); console.log(this.name); // Jake var result = new testThis(); // 谁被new,指向谁 console.log('第三个this=', this); // this指向构造函数 console.log(result.name); // jakezhang console.log(result.sayName()); // jakezhang testThis();
 console.log('第四个this=', this); console.log(this.name); // jakezhang

解析:

1.第一个this:在全局范围内,this指向window对象;

 所以this.name = 'Jake';指向最外层的name

2.第二个this:有new关键字,但是我认为相当于是window来进行调用的,也就是谁被new,指向谁;此时也就是指向window

 所以this.name = 'Jake'

3.第三个this:相当于生成一个构造函数,并赋值给result,此时还是谁被new,指向谁。this指向testThis();

 result.name = 'jakezhang';

4.第四个this:调用testThis()函数,this指向函数内部

 this.name = 'jakezhang'

原文地址:https://www.cnblogs.com/liumcb/p/14061388.html