「这是我参与2022首次更文挑战的第26天,活动详情查看:2022首次更文挑战」
JavaScript中的this用法
this是什么?
this是JavaScript中的一个关键字,在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。
而一些面向对象语言中 this 表示当前对象的一个引用。JavaScript中的this表示的是当前执行环境对象
1. 直接使用this
直接使用时,this代表全局对象,在浏览器中全局对象就是window
const a = this
console.log(a) // window
2. 纯粹函数调用中的this
t这时this表示的是函数所属者,也就是window对象
function myFunction() {
return this;
}
console.log(myFunction()) // window
注意:严格模式下this表示undefined
3. 方法中的this
在对象方法中,this表示方法所属的对象,下面this表示的就是a这个对象
let a = {
age: 18,
name: "阿花",
like: function() {
return this.name + "喜欢滑板"
}
}
console.log(a.like()) // 阿花喜欢滑板
4. 事件绑定中的this
在绑定事件中,this 表示事件所属的元素
假如在html元素上绑定了一个点击事件,那么这个点击事件中this指向的就是绑定事件的html元素
<div style="background-color: red;" onclick="this.style= 'background-color : green' ">
点我变色
</div>
5. 构造函数中的this
生成新的构造函数时,this表示这个新的对象。
function obj() {
this.a = 1;
}
var obj1 = new obj();
obj1.a = 3
console.log(obj1.a) // 3
6. apply,call 调用
在 JavaScript 中函数也属于对象,有方法apply 和 call ,可以切换函数执行的上下文环境(context),即 this 绑定的对象。
var a = {
name : "阿花",
age : 18,
fn : function() {
return this.name + "今年" + this.age + "岁了";
}
}
var b = {
name:"张三",
age: 21,
}
a.fn.call(b); // 张三今年21岁了
这时this表示的是call的参数,也就是b对象。