ES this的问题

浏览器环境

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this</title>
</head>
<body>
    <script>
        var age = 100
        var rick = {
            age: 30,
            name: 'Rick',
            grow() {
                console.log(`I am ${this.name}, I am ${this.age}`) // age: 30
                setTimeout(function() {
                    console.log(`I am ${this.age}`) // 100
                    console.log(`I am ${window.age}`) // 100
                    console.log(`I am ${age}`) // 100
                    console.log(window === this) // true
                }, 100)

            }
        }

        rick.grow()

        function testThis(param) {
            console.log(param + '. this === window => ' +  (this === window))
        }

        testThis(1) // 作为一个函数的话 this指向global,浏览器环境下就是window
        new testThis(2) // 作为一个对象的话 this指向对象

    </script>
</body>
</html>

node环境

// let age = 100;
age = 100

let rick = {
    age: 30,
    name: 'Rick',
    grow() {
        // console.log(`I am ${this.name}, I am ${this.age}`) // age: 30
        setTimeout(function() {
            console.log(`I am ${this.age}`) // 使用bind(this) age: 30. 否则this函数自身的this
            // console.log(this)

            // for (let k in this) {
            //     console.log(k)
            // }
        }.bind(this), 1001)

    }
}

// rick.grow()

// 数组复制
let a = [1, 2]
let b = [...a]
console.log(b)

// 对象复制
let user = {
    name: 'Jame'
}

let c = Object.assign({}, user) 
console.log(c)
let d = {...user}
console.log(d)

// 数组转函数参数
function test(a, b) {
    console.log(`a: ${a}, b: ${b}`)
    console.log(`2.this => ${this}`)
}
console.log(test(...a))
console.log(test.apply(null, a)) // apply的作用

console.log(`1.this => ${this}`)