码迷,mamicode.com
首页 > 其他好文 > 详细

this指向问题

时间:2020-12-04 11:30:19      阅读:6      评论:0      收藏:0      [点我收藏+]

标签:赋值   zhang   函数   第一个   调用   sha   res   关键字   构造函数   

经常在代码中使用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‘

 

this指向问题

标签:赋值   zhang   函数   第一个   调用   sha   res   关键字   构造函数   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!