返回
this在javascript函数中的应用
前端
2024-01-14 07:17:47
this在javascript函数中无处不在,相信很多初学者都会感觉this十分复杂,其实只要掌握了this的两个基本指向原则——谁引用它它就指向谁与就近原则。
this在javascript中的作用域和普通变量的作用域是不同的,javascript函数中的this并不一定引用它的声明者,因此在理解this关键字时要跳出常规思
路。
this在javascript中的指向问题主要围绕以下几个场景展开:
1、普通函数调用:
当我们以普通函数的形式直接调用一个方法时,这里的this指向global对象(浏览器环境下),而严格模式下this为undefined。
2、方法调用:
当我们使用对象的方法时,此时this指向该对象。
3、构造函数调用:
当我们使用new关键字调用构造函数时,此时this指向创建的新对象。
4、事件处理函数调用:
当我们使用addEventListener()方法为元素绑定事件时,此时this指向触发事件的元素。
5、箭头函数调用:
箭头函数没有自己的this,它的this由外层函数决定。
6、call/apply/bind调用:
call/apply/bind方法可以改变函数的this指向。
因此,只有当函数被当做对象的方法调用时,this指向这个对象;反之,如果函数以独立函数的形式调用,那么this指向window对象。下面是几个示例:
function Person(name) {
this.name = name;
this.greet = function() {
console.log(Hello, my name is ${this.name}
);
};
}
const person = new Person('John');
person.greet(); // Hello, my name is John
在上面的示例中,`this`在`greet`函数中指向`person`对象,因为`greet`函数是作为`person`对象的方法被调用的。
function greet() {
console.log(Hello, my name is ${this.name}
);
}
greet(); // Hello, my name is undefined
在上面的示例中,`this`在`greet`函数中指向`window`对象,因为`greet`函数是以独立函数的形式被调用的。
## 总结
`this`关键字在javascript函数中非常重要,它用于引用当前对象。在函数中,`this`的指向取决于函数的调用方式。如果函数作为对象的方法被调用,那么`this`指向该对象。如果函数作为独立函数被调用,那么`this`指向`window`对象。