前言
歡迎關注 『前端進階圈』 公眾號 ,一起探索學習前端技術......
前端小菜雞一枚,分享的文章純屬個人見解,若有不正確或可待討論點可隨意評論,與各位同學一起學習~
聊聊對 this 對象的理解?
定義
- 在執行上下文中的一個屬性,它指向最後一次調用這個屬性或方法的對象。通常有四種情況來判斷。
四種情況如下
1. 函數調用模式:當一個函數不是一個對象的屬性時,直接作為函數來調用時, 嚴格模式下指向 undefined, 非嚴格模式下,this 指向全局對象。
// 嚴格模式
"use strict";
var name = "window";
var doSth = function () {
console.log(typeof this === "undefined");
console.log(this.name);
};
doSth(); // true,// 報錯,因為this是undefined
// 非嚴格模式
let name2 = "window2";
let doSth2 = function () {
console.log(this === window);
console.log(this.name2);
};
doSth2(); // true, undefined
2. 方法調用模式:如果一個函數作為一個對象的方法來調用時,this 指向當前這個對象
var name = "window";
var doSth = function () {
console.log(this.name);
};
var student = {
name: "lc",
doSth: doSth,
other: {
name: "other",
doSth: doSth,
},
};
student.doSth(); // 'lc'
student.other.doSth(); // 'other'
// 用call類比則為:
student.doSth.call(student);
// 用call類比則為:
student.other.doSth.call(student.other);
3. 構造器調用模式:如果一個函數通過 new 調用時,函數執行前會新創建一個對象,this 指向這個新創建的對象。
var Obj = function (p) {
this.p = p;
};
var o = new Obj("Hello World!");
o.p; // "Hello World!"
4. apply, call, bind 模式:顯式更改 this 指向,嚴格模式下,指向綁定的第一個參數,非嚴格模式下,null 和 undefined 指向全局對象(瀏覽器中是 window),其餘指向被 new Object() 包裹的對象。
aplly: apply(this綁定的對象,參數數組)func.apply(thisValue, [arg1, arg2, ...])
function f(x, y) {
console.log(x + y);
}
f.call(null, 1, 1); // 2
f.apply(null, [1, 1]); // 2
call: call(this綁定的對象,一個個參數)func.call(thisValue, arg1, arg2, ...)
var doSth = function (name) {
console.log(this);
console.log(name);
};
doSth.call(2, "lc"); // Number{2}, 'lc'
var doSth2 = function (name) {
"use strict";
console.log(this);
console.log(name);
};
doSth2.call(2, "lc"); // 2, 'lc'
bind: bind(this綁定的對象)func.bind(thisValue)
var counter = {
count: 0,
inc: function () {
this.count++;
},
};
var obj = {
count: 100,
};
var func = counter.inc.bind(obj);
func();
obj.count; // 101
// eg2:
var add = function (x, y) {
return x * this.m + y * this.n;
};
var obj = {
m: 2,
n: 2,
};
var newAdd = add.bind(obj, 5);
newAdd(5); // 20
箭頭函數規則
- 不會使用以上原則,而是根據當前作用域來決定
this, 也就是説箭頭函數會繼承外層函數,調用的this綁定,沒有外層函數,則是指向全局(瀏覽器中是window)。
this 優先級
構造器模式 > apply, call, bind > 方法調用模式 > 函數調用模式
文章特殊字符描述:
- 問題標註
Q:(question) - 答案標註
R:(result) - 注意事項標準:
A:(attention matters) - 詳情描述標註:
D:(detail info) - 總結標註:
S:(summary) - 分析標註:
Ana:(analysis) - 提示標註:
T:(tips)
往期回顧:
- 熱點面試題:瀏覽器和Node的宏任務和微任務?
- 這是你理解的CSS選擇器權重嗎?
- 熱點面試題:JS 中 call, apply, bind 概念、用法、區別及實現?
- 熱點面試題: 常用位運算方法?
- Vue數據監聽Object.definedProperty()方法的實現
- 熱點面試題:Virtual DOM 相關問題?
- 熱點面試題: Array中有哪些非破壞性方法?
-
熱點面試題:協商緩存和強緩存的理解及區別?
最後:
- 歡迎關注 『前端進階圈』 公眾號 ,一起探索學習前端技術......
- 公眾號回覆 加羣 或 掃碼, 即可加入前端交流學習羣,長期交流學習......
- 公眾號回覆 加好友,即可添加為好友