Javascript中的this指向

function函数

1 默认指向

全局调用函数,函数体内的this指向window对象

num = 1
function testfunc(){
     console.log(this)
     console.log(this.num);
 }
 testfunc()
Window {window: Window, self: Window, document: document, name: "", location: Location,}
this.html:14 1

严格模式下:this默认指向为undefined

 num = 1
 function testfunc(){
     'use strict'
     console.log(this)
     console.log(this.num);
 }
 testfunc()
undefined
this.html:15 Uncaught TypeError: Cannot read property 'num' of undefined
    at testfunc (this.html:15)
    at this.html:17
testfunc @ this.html:15
(anonymous) @ this.html:17

2 隐式指向

当一个函数在一个对象内被调用时,函数体内的this指向这个对象

num = 1
function testfunc(){
    console.log(this)
    console.log(this.num);
}
let obj = {
    num: 10,
    func: testfunc
}
obj.func()
{num: 10, func: ƒ}
10

3 显示指向

使用call apply bind可以改变this的指向


num = 1
function testfunc(){
    console.log(this)
    console.log(this.num);
}
let obj = {
    num: 10,
    func: testfunc
}
let objA = {
    num: 199
}
obj.func.call(objA)

{num: 199}
199

4 构造函数

function Persion(name){
    this.name = name
    this.hello = function(){
        console.log(this)
        console.log('hello'+this.name)
    }
}
let p1 = new Persion('xiaobai')
p1.hello()
Persion {name: "xiaobai", hello: ƒ}hello: ƒ ()name: "xiaobai"__proto__: Object
this.html:15 helloxiaobai

箭头函数

一层一层找到最上层的函数调用

 function fa(){
            setInterval(t=>{console.log(this)},1000)
        }
        fa();

箭头函数中的this会一层一层向上找到最上层函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kobe_OKOK_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值