all-of-frontend/Answer/11-20/16.md

21 lines
739 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

```js
let length = 10
function fn() {
console.log(this.length);
}
let obj = {
length: 5,
method(fn) {
// 两次调用各输出什么
fn()
arguments[0](0)
}
}
obj.method(fn, 1)
```
这道题目核心是在考 `this` 的指向,但是还有一些别的坑。
执行第一次 `fn` 的时候,这时候的 `this` 就是 `window`,但是 `window.length` 并不是指向用 `let` 声明的 `length` 上的,而是「返回当前窗口中包含的框架数量(框架包括frame和iframe两种元素)」,具体可以参考 [文档](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/length)。
执行第二次 `fn` 的时候,此时 `this``arguments``arguments.length` 为实参的长度,也就是 2。