每日3題
34 以下代碼執行后,控制臺中的輸出內容為?
const num = {
a: 10,
add() {
return this.a + 2;
},
reduce: () => this.a - 2,
};
console.log(num.add());
console.log(num.reduce());
35 以下代碼執行后,控制臺中的輸出內容為?
var x = 1;
if (function f() {}) {
x += typeof f;
}
console.log(x);
36 以下代碼執行后,控制臺中的輸出內容為?
function f() {
return f;
}
console.log(new f() instanceof f);
- 公眾號【今天也要寫bug】更多前端面試題
答案及決議
34
// 答案:12 NaN
// 考察普通函式和箭頭函式中 this 的區別
// 普通函式中的 this 是運行時決定
// 箭頭函式中的 this 是編譯時就決定了的
const num = {
a: 10,
add() {
return this.a + 2;
},
reduce: () => this.a - 2,
};
console.log(num.add()); // 隱式系結:this 指向 num,因此輸出 12
console.log(num.reduce());
// 箭頭函式:this 指向 window,window 上沒有屬性 a
// 所以 this.a=undefined,最終輸出 NaN
35
// 答案:1undefined
// 考察型別轉換、typeof、加法賦值
var x = 1;
// if 條件中的 function f() {} 是 truthy 值
// 所謂 truthy(真值)指的是在布林值背景關系中,轉換后的值為 true 的值
// 所有除 false、0、-0、0n、""、null、undefined 和 NaN 以外的皆為真值
// 關于 truthy 和 falsy 的詳細說明,可查閱 MDN 檔案
if (function f() {}) {
x += typeof f;
}
// typeof 回傳的是一個字串
// 加法賦值運算子 (+=) 將右運算元的值添加到變數,并將結果分配給該變數,
// 即先使用相加運算(+)得到結果,再賦值
// 相加運算子 (+) 用于對兩個運算元進行相加運算,如果運算元中有一方為字串,
// 則該運算子將兩個運算元連接成一個字串,
console.log(x); // 綜上,最終輸出 1undefined
36
// 答案:false
// 考察 new、原型鏈、instanceof
function f() {
return f;
}
console.log(new f() instanceof f);
// new 運算子:如果建構式顯式回傳一個物件,則該物件會覆寫 new 創建的物件
// new f() 得到的物件是 f
// instanceof 方法:判斷函式(右)的 prototype 屬性是否會出現在物件(左)的原型鏈上
// new f() instanceof f,即 f instanceof f
// 顯然 f 的 prototype 屬性不會出現在 f 的原型鏈上
// f.__proto__ => Function.prototype
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507231.html
標籤:其他
