JS-this的指向

this的指向

this的指向分类

1.默认指向

this默认指向的是window对象

    console.log(this);
    //该语句为打印语句,可以从结果看出当前this指代的是window对象
2.函数调用时

1.独立调用 this 指向 window 对象

2.函数如果作为某个对象的方法时: this 指向的是当前对象.

function test(){
    console.log(this);
}

test();
divObj.test();
//独立调用的时候 (谁调用函数,this就指向谁)
//test() = window.test()
3.指向当前对象

this存在于类中时,this指向当前对象

let Obj = {
    show:function(){
        console.log(this);
    }
}
obj.show();
//show方法属于波及对象,所以方法中的this指向obj对象

//注意
let showNew = obj.show();
showNew();
//这时this指代window
//类似let showNew = function(){}
5.his指向绑定的元素

当函数作为一个事件处理函数的时候,这时this是指向绑定的元素

 

*注意:箭头函数()=>{},箭头函数的 this的指向 它的this指向始终是指向的外层作用域

改变this的指向

  1. call(更改对象,函数参数1,函数参数2,...)

  2. apply(更改对象,[函数参数1,函数参数2,...])

  3. let 接收函数名 = bind(更改对象)

let obj_1 = {
    num:10,
    add:function(x,y){
        console.log(this.num + x +y);
    }
}

let obj_2 = {
    num:20,
}

obj_1.add(5,20);
//结果为35

obj_1.add.call(obj_2,5,20);
obj_1.add.apply(obj_2,[5,20]);
let add_2 = obj_1.add.bind(obj_2);
add_2(5,20);
//以上三种打印的结果为 45 
//因为上诉方法改变了this的指向使得 this.num的值发生

猜你喜欢

转载自www.cnblogs.com/-Archenemy-/p/12571822.html