关于js种this 的指针

1. 给当前元素的某个事件绑定方法,方法中的this 都是当前操作的元素本身

 document.body.onclick = function () {

 //this : body
}

 

2. 函数执行,看函数前面是否有点,有的话点前面的this 就是谁,没有点, this就是window 在js的严格模式下,没有点的this是undefined

let fn = function () {
    console.log(this.name)
};
let obj = {
    name : 'hh',
    fn: fn
};
fn(); //this: window
obj.fn();//this : obj

3.构造函数执行 方法中的this 一般都是当前类的实例

let Fn = function () {

this.x = 100; //this:f

}

let f = new Fn;

4.箭头函数中没有自己的this this 是上下文中的this

let obj = {

fn: function() {

   setTimeout(() => {

    //this: obj

     },1000);

   }

}
obj.fn();

5.在小括号表达式中 会影响this 的指向


let obj = {

    fn:function () {

     console.log(this);

    }

};

obj.fn(); //this : obj

(23, obj.fn)();//this :window

6.使用call/apply/bind可以改变 this 指向


fn.call(obj);//this obj

fn.call(12);//this :12

fn.call(); //this:window 非严格模式下call/apply/bind第一个参数不写或者写 null和undefined this都是window 严格模式下写谁this 就是谁,不写是undefined

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值