JavaScript中的this關鍵詞指向
更新時間:2022年05月25日 08:23:34 作者:??SilentLove????
本文介紹了JavaScript中的this關鍵詞指向,this是JavaScript的一個關鍵字,他是函數(shù)執(zhí)行過程中,自動生成的一個內(nèi)部對象,指當前的對象,只在當前函數(shù)內(nèi)部使用,更多相關資料需要的小伙伴可以參考下面文章內(nèi)容
1、es5中的this的指向
this是JavaScript的一個關鍵字,他是函數(shù)執(zhí)行過程中,自動生成的一個內(nèi)部對象,指當前的對象,只在當前函數(shù)內(nèi)部使用。- 在
es5中this的指向取決于函數(shù)運行時的環(huán)境。 - 沒有直接掛載者(或稱調(diào)用者)的函數(shù)中
this,非嚴格模式下指向window,在use strict嚴格模式下,默認為undefined。以下都是在非嚴格模式下討論
var name = 'hello window!';
var obj = {
name: 'hello obj!',
fn: function() {
console.log(this.name);
}
};
var fn = obj.fn;
fn(); // hello window!
obj.fn(); // hello obj!obj.fn()在執(zhí)行時,fn中的this指向的是當前的調(diào)用對象obj。fn()執(zhí)行時,this指向的是window對象。
var fn = obj.fn; // 等價于 window.fn = obj.fn; fn(); // 等價于 window.fn();
匿名函數(shù)的執(zhí)行環(huán)境是全局的
var name = 'hello window!';
var obj = {
name: 'hello obj!',
fn: function() {
console.log(this.name); // 'hello obj!'
return function() {
console.log(this.name); // 'hello window!'
};
}
};
obj.fn()();2、es6中的this
es6箭頭函數(shù)的特點
- 箭頭函數(shù)沒有自己的
this - 函數(shù)體內(nèi)的
this對象,就是定義時所在的對象,而不是使用時所在的對象,即外層代碼的this引用。 - 不可以當作構造函數(shù),也就是說,不可以使用
new命令,否則會拋出一個錯誤。 - 沒有
arguments對象。如果要用,可以用Rest參數(shù)代替。 - 不可以使用
yield命令,因此箭頭函數(shù)不能用作Generator函數(shù)
示例說明,修改上述示例代碼中的函數(shù)為箭頭函數(shù):
// 示例代碼1
var name = 'hello window!';
var obj = {
name: 'hello obj!',
fn: () => {
console.log(this.name); // 這里的this指向的外層的this,即window對象,想當于上打印的是console.log(window.name);
}
};
var fn = obj.fn;
fn(); // hello window!
obj.fn(); // hello window!
// 示例代碼2
var name = 'hello window!';
var obj = {
name: 'hello obj!',
fn: function() {
console.log(this.name); // hello obj!
return () => {
console.log(this.name); // hello obj! // this指向外層的this,即obj對象
};
}
};
obj.fn()();總結:
es5中的this主要看運行的環(huán)境,指向的是調(diào)用它的對象。- 箭頭函數(shù)中的
this是在一開始就固定的,并不受調(diào)用對象
到此這篇關于JavaScript中的this關鍵詞指向的文章就介紹到這了,更多相關js的this指向內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
TypeScript在Vuex4中使用TS實戰(zhàn)分享
這篇文章主要介紹了TypeScript在Vuex4中使用TS實戰(zhàn)分享,vuex4類型?Api分析和vuex4實戰(zhàn)兩部分講述,需要的小伙伴可以參考一下2022-06-06

