(JS five)this 指向总结

当作为函数直接调用时, this => window
当作为构造函数时,this => 构造出的实例对象
当作为对象的方法调用时,this => 调用方法的那个对象
使用call、apply、bind方法时,this => 法中指定的对象(传入的第一个参数)
函数调用时无任何调用前缀,this => window
箭头函数的this, this => 就是外层函数的this

1.当作为函数直接调用时, this => window#

// 当作为函数,直接调用时
// this ===> 在非严格模式下,全局对象window;  严格模式下是undefiend
Person('red')   // this => window

2.当作为构造函数时,this => 构造出的实例对象#

// 当作为构造函数时
// this ===> 构造出的实例对象
var fitz = new Person('pink')   // this => fitz

3当作为对象的方法调用时,this => 调用方法的那个对象#

// 当作为对象的方法调用时
// this ===> 调用方法的那个对象
fitz.getColor()     // this => fitz

4使用call、apply、bind方法时,this => 法中指定的对象(传入的第一个参数)#

// 当使用call、apply、bind方法时
// this ==> 方法中指定的对象(传入的第一个参数)
var lx = {}
fitz.setColor.call(lx, 'blue')  // this => lx
console.log(lx)     // lx {color: "blue"}

5函数调用时无任何调用前缀,this => window#

// 函数调用时无任何调用前缀
// this ==> window

/* 
    原因: 执行func1相当于执行在函数外部执行func2()
*/
function func1 () {
    function func2 () {
        console.log(this)
    }
    func2()     // 无任何调用前缀
}
func1()     // this => window

6箭头函数的this, this => 就是外层函数的this#
准确的来说, 箭头函数自己没有this, 在箭头函数中的this会像作用域链一样像外层逐层查找, 箭头函数的this就是它外层函数的this

// 例子1
/* 
    这个例子中,箭头函数的this是外层函数test1的this
    外层函数test1的this => window
    所以console.log(this.msg) <=> console.log(window.msg)
*/
window.msg = '测试箭头函数的this'
function test1 () {
    (() => {
        console.log(this.msg)
    })()
}
test1()  // 测试箭头函数的this
// 例子2
function test2 () {
    return () => {
        console.log(this.name)
    }
}
var obj = {
    name: 'Fitz',
    receiveFunc: test2()
}
var receiveFunc = test2.call(obj)
/* 
执行完上述语句的状态是:
    - 用call方法显示执行函数test2, 得到一个箭头函数
    - 同时test2的this从window强制绑定后变成obj

*/
receiveFunc()
注意: 箭头函数的this一旦确定无法更改,但是可以通过改变外层函数的this然后曲线更改箭头函数的this

// 例子3
function test3 () {
     return () => {
         console.log(this)
     }
}
var obj2 = {}
var receiveFunc2 = test3()
receiveFunc2.call(obj2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值