JavaScript 中 this 的指向取決于函數(shù)調(diào)用方式,在全局執(zhí)行環(huán)境中,this指向全局對(duì)象。但在嚴(yán)格模式("use strict")下,this在全局上下文中不會(huì)自動(dòng)綁定到全局對(duì)象,而是會(huì)成為undefined。理解 this 需結(jié)合調(diào)用棧和綁定規(guī)則,箭頭函數(shù)是例外,其余情況均由調(diào)用方式動(dòng)態(tài)決定。
javascript中this指向有幾種情況?
在 JavaScript 中,this 的指向取決于函數(shù)的調(diào)用方式,主要分為以下 5 種情況:
1. 默認(rèn)綁定
規(guī)則:非嚴(yán)格模式下,this 指向全局對(duì)象(瀏覽器中是 window,Node.js 中是 global);嚴(yán)格模式下,this 為 undefined。
示例:
javascriptfunction foo() {console.log(this); // 非嚴(yán)格模式: window;嚴(yán)格模式: undefined}foo();
2. 隱式綁定
規(guī)則:this 指向調(diào)用該方法的對(duì)象。
示例:
javascriptconst obj = {name: "Alice",greet() {console.log(this.name); // "Alice"(this 指向 obj)}};obj.greet();
注意:若方法被賦值給變量后調(diào)用,this 會(huì)丟失綁定(指向全局或 undefined):
javascriptconst bar = obj.greet;bar(); // 非嚴(yán)格模式: window;嚴(yán)格模式: undefined
3. 顯式綁定
規(guī)則:通過 call、apply 或 bind 強(qiáng)制指定 this。
示例:
javascriptfunction greet() {console.log(this.name);}const user = { name: "Bob" };greet.call(user); // "Bob"(this 顯式綁定為 user)
bind 特殊點(diǎn):返回一個(gè)新函數(shù),永久綁定 this:
javascriptconst boundGreet = greet.bind(user);boundGreet(); // "Bob"
4. new 綁定
規(guī)則:this 指向新創(chuàng)建的實(shí)例對(duì)象。
示例:
javascriptfunction Person(name) {this.name = name; // this 指向新創(chuàng)建的實(shí)例}const alice = new Person("Alice");console.log(alice.name); // "Alice"
5. 箭頭函數(shù)(詞法作用域)
規(guī)則:箭頭函數(shù)的 this 繼承自外層作用域,無法通過調(diào)用方式改變。
示例:
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();
關(guān)鍵記憶點(diǎn):
箭頭函數(shù)的 this 由定義時(shí)決定,其他情況由調(diào)用方式?jīng)Q定。
顯式綁定優(yōu)先級(jí)高于隱式綁定,new 綁定優(yōu)先級(jí)高于顯式綁定。
這三個(gè)方法可以用來顯式設(shè)置函數(shù)的this值。通過這些方法調(diào)用時(shí),可以指定this的值。call() 和 apply() 允許你為函數(shù)調(diào)用顯式指定 this 值。bind() 方法創(chuàng)建一個(gè)新的函數(shù)實(shí)例,這個(gè)實(shí)例的 this 被永久綁定到了 bind() 的第一個(gè)參數(shù),無論之后如何調(diào)用這個(gè)新函數(shù)。