<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body></body>
<script>
// this的指向
function fn() {
this.age = 22
console.log(this)
}
// 如果直接调用fn函数,this是window
fn() //打印 → Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
// 如果函数作为构造函数用,那么其中的this就代表它即将new出来的对象
let f1 = new fn() //打印 → fn {age: 22}
console.log(f1.age)
//apply改变this的指向
let obj = {
age: 25
}
function fnn() {
console.log(this)
}
fnn() //打印 → Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
fnn.apply(obj) //打印 → {age: 25}
// 闭包
function fn1() {
let str = '闭包'
console.log('fn1 →', str)
return function fn2() {
console.log('fn2抛出闭包 →', str)
}
}
// 调用方式1
fn1()() //打印 fn1 → 闭包 fn2抛出闭包 → 闭包
// 调用方式2
let fn3 = fn1()
fn3()
</script>
</html>