JavaScript中函数的this绑定有哪四种方式,大家能猜到吗?
- 内容介绍
- 文章标签
- 相关推荐
本文共计2497个文字,预计阅读时间需要10分钟。
JavaScript中的this和函数息息相关,今天,我就给大家详细地讲解一番:从this+,一直说到this,很多让人摸不着头脑的抽象概念也就跑出来了。这里,我只说最核心的一点——函数。
在JavaScript中,函数是基石。函数内部的this关键字,其指向取决于函数的调用方式。
1. 普通函数调用:此时,this指向全局对象(在浏览器中通常是window对象)。
javascriptfunction test() { console.log(this);}test(); // 输出:window 或全局对象
2. 对象方法调用:此时,this指向调用该方法的对象。
javascriptconst obj={ name: '张三', sayName: function() { console.log(this.name); }};obj.sayName(); // 输出:张三
3. 构造函数调用:此时,this指向新创建的对象。
javascriptfunction Person(name) { this.name=name;}const person=new Person('李四');console.log(person.name); // 输出:李四
4. Function构造函数调用:此时,this指向全局对象。
javascriptconst func=new Function('console.log(this)');func(); // 输出:window 或全局对象
5. 箭头函数调用:此时,this指向箭头函数定义时的上下文。
本文共计2497个文字,预计阅读时间需要10分钟。
JavaScript中的this和函数息息相关,今天,我就给大家详细地讲解一番:从this+,一直说到this,很多让人摸不着头脑的抽象概念也就跑出来了。这里,我只说最核心的一点——函数。
在JavaScript中,函数是基石。函数内部的this关键字,其指向取决于函数的调用方式。
1. 普通函数调用:此时,this指向全局对象(在浏览器中通常是window对象)。
javascriptfunction test() { console.log(this);}test(); // 输出:window 或全局对象
2. 对象方法调用:此时,this指向调用该方法的对象。
javascriptconst obj={ name: '张三', sayName: function() { console.log(this.name); }};obj.sayName(); // 输出:张三
3. 构造函数调用:此时,this指向新创建的对象。
javascriptfunction Person(name) { this.name=name;}const person=new Person('李四');console.log(person.name); // 输出:李四
4. Function构造函数调用:此时,this指向全局对象。
javascriptconst func=new Function('console.log(this)');func(); // 输出:window 或全局对象
5. 箭头函数调用:此时,this指向箭头函数定义时的上下文。

