在JavaScript中,this
關(guān)鍵字指向當(dāng)前執(zhí)行上下文的對(duì)象。它通常在對(duì)象方法中使用,表示該方法所屬的對(duì)象。
在函數(shù)中使用this
,它的值取決于函數(shù)是如何被調(diào)用的。有以下幾種情況:
- 普通函數(shù)調(diào)用:在普通函數(shù)中,
this
指向全局對(duì)象(在瀏覽器中是window
)。
function func() {
console.log(this); // 輸出全局對(duì)象
}
func();
- 方法調(diào)用:在對(duì)象的方法中使用
this
,它指向調(diào)用該方法的對(duì)象。
var obj = {
name: 'John',
sayHello: function() {
console.log('Hello, ' + this.name); // 輸出 Hello, John
}
};
obj.sayHello();
- 構(gòu)造函數(shù)調(diào)用:在構(gòu)造函數(shù)中,
this
指向新創(chuàng)建的對(duì)象實(shí)例。
function Person(name) {
this.name = name;
this.age = 0;
}
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name); // 輸出 Hello, John
};
var john = new Person('John');
john.sayHello();
- 箭頭函數(shù):箭頭函數(shù)不綁定自己的
this
值,它繼承自父執(zhí)行上下文。這意味著箭頭函數(shù)中的this
值取決于它被定義時(shí)的上下文,而不是它被調(diào)用時(shí)的上下文。例如:
var obj = {
name: 'John',
sayHello: () = > {
console.log('Hello, ' + this.name); // 輸出 undefined
}
};
obj.sayHello();
在這個(gè)例子中,箭頭函數(shù)沒有自己的this
值,所以它繼承了父執(zhí)行上下文的this
值,即obj
對(duì)象。因此,在箭頭函數(shù)中使用this
,它指向的是obj
對(duì)象,而不是箭頭函數(shù)本身。
-
瀏覽器
+關(guān)注
關(guān)注
1文章
1040瀏覽量
36051 -
函數(shù)
+關(guān)注
關(guān)注
3文章
4367瀏覽量
64065 -
javascript
+關(guān)注
關(guān)注
0文章
525瀏覽量
54456 -
this
+關(guān)注
關(guān)注
0文章
5瀏覽量
3320
發(fā)布評(píng)論請(qǐng)先 登錄
JavaScript教程
JavaScript無處不在
JavaScript中的Object
JavaScript中的this是什么?
JavaScript 簡介
JavaScript源碼大全(CHM)

評(píng)論