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方法即可更改指向
文章详细阐述了JavaScript中this的关键概念,包括它在不同场景下的指向:直接调用函数时指向全局对象,作为对象方法时指向调用对象,构造函数中指向新实例,匿名函数和定时器中同样指向全局对象,箭头函数则遵循上下文的this。此外,文中还提到了DOM事件处理函数中的this行为以及如何通过bind、call、apply改变this的指向。

被折叠的 条评论
为什么被折叠?



