js中关于this的指向问题

this代表谁

首先我们要清楚的认识到一个点,this只有在函数调用的时候才会出现,代表的是调用函数时的那个对象

也就是说,A调用了某函数,那么对应的这个函数中的this就代表A;

使用这里一定要清楚的知道一个点,很多初学者js的同学经常弄错:

this不指向函数本身,当然也不指向函数的作用域!!!

各个场景中的this

1、直接调用函数,this指向全局对象

var name1 = 'mahk1';
function hello () {
  var name = 'mahk2';
  console.log('hello' + this.name);
}
hello();  // hello mahk1

刚才我们上面说了,谁调用函数,谁就是this,但是你看上面的试例,“没人去调用呀”

真的没人吗?肯定不是呀,次数是不是这个js文件在调用这个hello函数,所以this代表的就是module.exports,如果你文件运行在浏览器上,那么this就代表window,取决你运行的环境啦

2、对象的方法,this指向该对象

var name = 'mahk1';
var sayHello = {
  name: 'mahk2';
  hello1: function() {
    console.log('hello ' + this.name);
  }
	newHello: {
    name: 'mahk3';
    hello2: function() {
      console.log('hello ' + this.name);
    }
  }
}
sayHello.hello1();  // hello mahk2
sayHello.newHello.hello2();  // hello mahk3

反正你就认死谁调用函数,谁就是this

例如上面

hello1是sayHello调用的,所以this是sayHello;

hello2是newHello调用的,所以this是newHello;

3、构造函数,this指向实例化的新对象

var name = 'mahk2';
function People() {
  this.name = 'mahk2';
  this.sex = 'box';
}
var people = new People();
console.log(people);  // {name: 'mahk2', sex: 'box'}
console.log(people.name);  // mahk2

4、匿名函数调用,this都是指向全局对象

var name = 'mahk1';
var sayHello = {
  name:'mahk2',
  hello:(function(){
    console.log('hello ' + this.name); // hello mahk1
  })()
}
sayHello.hello;
 

5、定时器中调用,指向的是全局对象

var name = 'mahk1';
var sayHello = setTimeout(funtion() {
  var name = 'mahk2';
  console.log('hello ' + this.name);  // hello mahk1
}, 1000);

ps:定时器本质也是一种匿名函数的形式;

6、箭头函数调用,this指向的是“最近一层非箭头函数的this”,否则this的值则被设置为“全局对象”

var name = 'mahk';
var student = {
    name: 'mahk1',
    doSth: function(){
        var name = 'mahk2'
        var arrowDoSth = () => {
            console.log(this.name);
        }
        arrowDoSth();
    },
    arrowDoSth2: () => {
        console.log(this.name);
    }
}
student.doSth(); // 'mahk1'
student.arrowDoSth2(); // 'mahk'

7、DOM事件处理函数调用,this指向的是绑定事件的对应元素

<button class="button">onclick</button>
<ul class="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<script>
    var button = document.querySelector('button');
    button.onclick = function(ev){
        console.log(this);
        console.log(this === ev.currentTarget); // true
    }
    var list = document.querySelector('.list');
    list.addEventListener('click', function(ev){
        console.log(this === list); // true
        console.log(this === ev.currentTarget); // true
        console.log(this);
    }, false);
</script>

那么有没有什么方法可以改变函数中this的指向呢?

通过bind、call、apply方法即可更改指向​​​​​​​

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值