JavaScript 中 this 的指向取决于函数调用方式,在全局执行环境中,this指向全局对象。但在严格模式("use strict")下,this在全局上下文中不会自动绑定到全局对象,而是会成为undefined。理解 this 需结合调用栈和绑定规则,箭头函数是例外,其余情况均由调用方式动态决定。
javascript中this指向有几种情况?
在 JavaScript 中,this 的指向取决于函数的调用方式,主要分为以下 5 种情况:
1. 默认绑定
规则:非严格模式下,this 指向全局对象(浏览器中是 window,Node.js 中是 global);严格模式下,this 为 undefined。
示例:
javascriptfunction foo() {console.log(this); // 非严格模式: window;严格模式: undefined}foo();
2. 隐式绑定
规则:this 指向调用该方法的对象。
示例:
javascriptconst obj = {name: "Alice",greet() {console.log(this.name); // "Alice"(this 指向 obj)}};obj.greet();
注意:若方法被赋值给变量后调用,this 会丢失绑定(指向全局或 undefined):
javascriptconst bar = obj.greet;bar(); // 非严格模式: window;严格模式: undefined
3. 显式绑定
规则:通过 call、apply 或 bind 强制指定 this。
示例:
javascriptfunction greet() {console.log(this.name);}const user = { name: "Bob" };greet.call(user); // "Bob"(this 显式绑定为 user)
bind 特殊点:返回一个新函数,永久绑定 this:
javascriptconst boundGreet = greet.bind(user);boundGreet(); // "Bob"
4. new 绑定
规则:this 指向新创建的实例对象。
示例:
javascriptfunction Person(name) {this.name = name; // this 指向新创建的实例}const alice = new Person("Alice");console.log(alice.name); // "Alice"
5. 箭头函数(词法作用域)
规则:箭头函数的 this 继承自外层作用域,无法通过调用方式改变。
示例:
javascriptconst obj = {name: "Charlie",greet: () => {console.log(this.name); // 指向外层 this(如 window.name)},regularGreet() {const arrowFunc = () => console.log(this.name); // 继承外层 this(obj)arrowFunc(); // "Charlie"}};obj.regularGreet();
关键记忆点:
箭头函数的 this 由定义时决定,其他情况由调用方式决定。
显式绑定优先级高于隐式绑定,new 绑定优先级高于显式绑定。
这三个方法可以用来显式设置函数的this值。通过这些方法调用时,可以指定this的值。call() 和 apply() 允许你为函数调用显式指定 this 值。bind() 方法创建一个新的函数实例,这个实例的 this 被永久绑定到了 bind() 的第一个参数,无论之后如何调用这个新函数。