1.function函数:谁'调用'就指向谁
函数名() : 函数的this值指向window
对象名.方法名():函数的this值指向对象
new 函数名() :函数的this值指向实例对象
总结函数调用时
(1).看函数有没有new 有则是对象创建的,没new时则是window和对象
(2).在看有没有点,有点则是,点的左边是谁就是谁
(3).function函数没new没点都是window
2.箭头函数:没有this值
箭头函数的this值 指向上级作用域的this
function fn(){
console.log( this )
}
//普通函数
fn()// 指向window
//对象方法
let obj = {
eat:fn
}
obj.eat()// 指向obj
//构造函数 : 使用new来调用函数
new fn()// 指向实例对象
const obj1 = {
eat () {// eat:function(){}
// eat 是function, this指向obj
function fn1 () {
console.log(this)// window
}
fn1()
// fn2是箭头函数, this就是上级this obj
const fn2 = () => {
console.log(this)// obj
}
fn2()
},
say: () => {
// say是箭头函数, this就是上级window
function fn1 () {
console.log(this)//window
}
fn1()
const fn2 = () => {
console.log(this)//window
}
fn2()
}
}
obj1.eat()
obj1.say()