编辑代码

// 在浏览器环境中使用,jsrun中没有window对象
var name = 'jack'

// 箭头函数使this从“动态”变成“静态”,实质是内部没有this指向,继承上级对象this指向
// 箭头函数的this指向定义时外部作用域内的this指向
const obj1 = {
    age: 18,
    name: 'hanson',
    say: () => {
        console.log(`${this.name}, nihao`)
    }
}


const obj2 = {
    age: 18,
    name: 'hanson',
    // 普通函数的this指向调用时根据上下文取确认
    say() {
        console.log(`${this.name}, 你好`)
    }
}

const obj3 = {
    name: 'vincent'
}

obj1.say()
obj2.say()
obj2.say.call(obj3)

// 箭头函数作为匿名函数,没有prototype,没有自己的this指向,因此不能使用new构造函数
function mao(name, age) { //普通函数
    this.name = name
    this.age = age
    console.log('mao函数')
    return 1
}
var fn = (name, age) => ({ //箭头函数
    name: name,
    age: age
})

var b = new mao("浪漫主义码农", 100) //普通函数
console.log(b)
// var a = new fn("张三", 200) // 箭头函数,报错
// console.log(a)