浅谈javascript中的this指向问题

(前言:小编也是一个刚入行的小白,所以写不出来多么高深的东西,若有错误欢迎指证或者其他的什么相互验证,但是不接受大神的鄙视,谢谢,转载请注明出路)

1.给元素绑定事件时,this就是当前操作元素

    box.onclick=function () {
        console.log(this); // this => 单击的元素
    }

2.普通函数中,函数执行前面有点this就指代点前面的对象,没有点就指向全局window(非严格模式下),严格模式下为undefined

    function fn(){
        console.log(this);
    }
    let obj={};
    obj.fn=fn;
    fn() //=> this=>window,严格模式下为undefined
    obj.fn() // this=>window

3.构造函数中,this指向当次操作中的实例

    function Fn(){
        console.log(this); // this => Fn构造函数当前运行创建的实例
    }

4.全局环境下的this指向全局window

    console.log(this); // this => window

5.自执行函数中的this始终指向全局window

    ~(function () {
        console.log(this); // this => window
    })()

6.定时器回调函数中的this指向window

    setTimeout(function () {
        console.log(this); // this => window
    },5)

7.箭头函数中没有this,它的this取决于其上级作用域

 let f=()=>{
     console.log(this); // this => window
 }
 
 
 
 function fn() {
     console.log(this);
     let f=()=>{
         console.log(this); // this => obj
     }
     f();
 }
 let obj={name:'a'};
 obj.fn=fn;
 obj.fn();

8.可以使用Functionn基类原型上的call,apply,bind改变this 的指向

   fn.call(obj) => 将fn中的this指向改为obj,立即执行fn
   fn.apply(obj) => 将fn 中的this指向改为obj,立即执行fn
   fn.bind(obj) => 将fn中的this指向改为obj,并不立即执行而是预执行状态
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值