您现在的位置是:首页 > 编程语言学习 > 后端编程语言 > 文章正文 后端编程语言
javascript改变this指向的方法汇总
2022-09-16 10:02:42 后端编程语言
简介一、this指向this随处可见,一般谁调用,this就指向谁。this在不同环境下,不同作用下,表现的也不同。以下几种情况,this都是指向window1...
一、this指向
this随处可见,一般谁调用,this就指向谁。this在不同环境下,不同作用下,表现的也不同。
以下几种情况,this都是指向window
1、全局作用下,this指向的是window
- console.log(window);
- console.log(this);
- console.log(window == this); // true
2、函数独立调用时,函数内部的this也指向window
- function fun() {
- console.log('我是函数体');
- console.log(this); // Window
- }
- fun();
3、被嵌套的函数独立调用时,this默认指向了window
- function fun1() {
- function fun2() {
- console.log('我是嵌套函数');
- console.log(this); // Window
- }
- fun2();
- }
- fun1();
4、自调执行函数(立即执行)中内部的this也是指向window
- (function() {
- console.log('立即执行');
- console.log(this); // Window
- })()
需要额外注意的是:
构造函数中的this,用于给类定义成员(属性和方法)箭头函数中没有this指向,如果在箭头函数中有,则会向上一层函数中查找this,直到window二、改变this指向
1、call() 方法
call() 方法的第一个参数必须是指定的对象,然后方法的原参数,挨个放在后面。
(1)第一个参数:传入该函数this执行的对象,传入什么强制指向什么;(2)第二个参数开始:将原函数的参数往后顺延一位
用法: 函数名.call()
- function fun() {
- console.log(this); // 原来的函数this指向的是 Window
- }
- fun();
- function fun(a, b) {
- console.log(this); // this指向了输入的 字符串call
- console.log(a + b);
- }
- //使用call() 方法改变this指向,此时第一个参数是 字符串call,那么就会指向字符串call
- fun.call('call', 2, 3) // 后面的参数就是原来函数自带的实参
2、apply() 方法
apply() 方法的第一个参数是指定的对象,方法的原参数,统一放在第二个数组参数中。
(1)第一个参数:传入该函数this执行的对象,传入什么强制指向什么;(2)第二个参数开始:将原函数的参数放在一个数组中
用法: 函数名.apply()
- function fun() {
- console.log(this); // 原来的函数this指向的是 Window
- }
- fun();
- function fun(a, b) {
- console.log(this); // this指向了输入的 字符串apply
- console.log(a + b);
- }
- //使用apply() 方法改变this指向,此时第一个参数是 字符串apply,那么就会指向字符串apply
- fun.apply('apply', [2, 3]) // 原函数的参数要以数组的形式呈现
3、bind() 方法
bind() 方法的用法和call()一样,直接运行方法,需要注意的是:bind返回新的方法,需要重新调用是需要自己手动调用的
用法: 函数名.bind()
- function fun() {
- console.log(this); // 原来的函数this指向的是 Window
- }
- fun();
- function fun(a, b) {
- console.log(this); // this指向了输入的 字符串bind
- console.log(a + b);
- }
- //使用bind() 方法改变this指向,此时第一个参数是 字符串bind,那么就会指向字符串bind
- let c = fun.bind('bind', 2, 3);
- c(); // 返回新的方法,需要重新调用
- // 也可以使用下面两种方法进行调用
- // fun.bind('bind', 2, 3)();
- // fun.bind('bind')(2, 3);
上一篇:JavaScript使用useEffect模拟组件生命周期
下一篇:最后一页