this 的指向有哪些

1、普通函数中的this指向window

2、定时器中的this指向window

3、箭头函数没有this,它的this指向取决于外部环境、指向最近的的函数

4、事件中的this指向事件的调用者

5、 构造函数中this和原型对象中的this,都是指向构造函数new 出来实例对象

6、类 class中的this 指向由constructor构造器new出来的实例对象

7、自调用函数中的this 指向window

JavaScript 中,`this` 的指向取决于函数的调用方式,主要有以下几种情况: ### 全局作用域中 在全局作用域中,`this` 指向全局对象。在浏览器环境下,全局对象是 `window`;在 Node.js 环境中,全局对象是 `global`。 ```javascript console.log(this === window); // 在浏览器环境下输出 true ``` ### 函数调用 当函数作为普通函数调用时,`this` 指向全局对象。在严格模式下,`this` 为 `undefined`。 ```javascript function test() { return this; } console.log(test() === window); // 在浏览器环境下输出 true // 严格模式 function strictTest() { 'use strict'; return this; } console.log(strictTest() === undefined); // 输出 true ``` ### 方法调用 当函数作为对象的方法调用时,`this` 指向调用该方法的对象。 ```javascript var obj = { name: 'example', getName: function() { return this.name; } }; console.log(obj.getName()); // 输出 'example' ``` ### 构造函数调用 当使用 `new` 关键字调用函数时,`this` 指向新创建的对象。 ```javascript function Person(name) { this.name = name; } var person = new Person('John'); console.log(person.name); // 输出 'John' ``` ### `call`、`apply` 和 `bind` 方法调用 `call`、`apply` 和 `bind` 方法可以显式地指定 `this` 的指向。 ```javascript function greet(message) { console.log(message + ', ' + this.name); } var person1 = { name: 'Alice' }; var person2 = { name: 'Bob' }; // 使用 call 方法 greet.call(person1, 'Hello'); // 输出 'Hello, Alice' // 使用 apply 方法 greet.apply(person2, ['Hi']); // 输出 'Hi, Bob' // 使用 bind 方法 var greetPerson1 = greet.bind(person1); greetPerson1('Hey'); // 输出 'Hey, Alice' ``` ### 箭头函数 箭头函数没有自己的 `this`,它的 `this` 继承自外层函数。 ```javascript var obj = { name: 'example', arrowFunc: () => { return this.name; } }; console.log(obj.arrowFunc()); // 在浏览器环境下输出 '',因为 this 指向全局对象 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值