面試題1
let len = 10;
function fn() {
console.info(this.len)
}
fn(); // A
let Person = {
len: 5,
say: function() {
fn(); // B
arguments[0](); // C
}
}
Person.say(fn);
三處的輸出結果均為 undefined
A 處執行結果
- fn 的 this 指向為 window
- let 聲明的變量不掛載在 window 對象上
- 輸出結果為:window.len = undefined;
B處的執行結果
- say 函數的 this 指向為 Person
- fn 的 this 指向依然為 window
- 輸出結果依然為:window.len = undefined
C 處的執行結果
- arguments[0]() 相當於 arguments.fn()
- fn 的 this 指向為 arguments
- 輸出結果為:arguments.len = undefined
面試題2
var length = 10;
function fn() {
console.info(this.length)
}
fn(); // A
let Person = {
len: 5,
say: function() {
fn(); // B
arguments[0](); // C
}
}
Person.say(fn);
分別輸出 10, 10, 1
- A , B 處直接輸出 掛載到 window 對象下的 10
- C 處輸出 arguments.length = 1