什么是this
this可以为函数指向所有者,当函数作为对象属性时,将对象属性的函数叫做对象 方法,而对象就是该函数方法的所有者。
this作用
this用来调用对象属性,引用函数的所有者。
this用法
第一步:看this在哪里
1. 在全局作用域中
this 指向 window
注意:函数中 严格模式下 没有执行的时候先指向undefined,因为函数此时没有执行环境,在被调用的时候才指向window
console.log(this); //this = window
2. 在函数中,区分在什么函数中?
- 箭头函数
this 是 找上层作用域的this,因为箭头函数没有this,如果上层作用域为一个函数就按照下面的步骤指向,如果为全局则指向window。
var res = a => {
console.log(
this //window
);
};
console.log(res());
//箭头函数没有this 箭头函数中this 与上一层this相同
var obj = {
name:'yu',
say:function(){
var name = 'yang'
console.log(this);
var res = () =>{
console.log(this.name); //为上层函数的this,上层函数的this是obj,所以结果为yu
}
res()
}
}
obj.say()
- 事件处理函数
this 指向 触发事件的对也就是事件绑定给谁就指向谁。
<div id="Btn">我是按钮</div>
<script>
var btn = document.getElementById('Btn');
//this 在事件处理函数中 哪个元素 【触发】事件 ————>指向谁
btn.onclick = function(){
console.log('点击了');
console.log(this); //点击时button触发事件,所以this就是button
this.style.color = 'red';
}
</script>
- 构造函数
this 指向 构造函数创建的对象
//构造函数中this 指向创建的对象
function person(){ //普通函数
console.log(this); //构造函数 this是yyc 此时yyc是一个person函数,
this.name = arguments[0] //向yyc person对象中添加属性name但是arguments[0]没有,所以是undefined。
}
var yyc = new person();
console.log(yyc);
person();
3.除上面几种函数外,谁调用函数,函数中的this就指向谁。没有谁调用函数函数中的this指向window
var a=3;
var obj = {
a:2,
fire:function(){
var a = 3;
console.log(this.a); //2 obj调用fire函数 this指向obj obj.a = 2
function innerFire(){
var a = 4;
console.log(this.a); //3 window
}
//没有任何对象调用的时候 this指向window
//
innerFire();
console.log(this.a); //2
}
}
obj.fire()