this+解构

97 阅读1分钟

this的指向问题

1、每一个函数都有一个内置的this变量。this指向当前的函数主人,函数的主人要通过上下文来判断 常见的this: 1.全局的函数

function show(){
    alert(this)//this指向window
}
show()

2、this指向person

 var person = {
    username:"年后",
    age:23,
    show:function(){
        alert(person,username);
        alert(this.username);
    }
}
    person.show();

3、this指向button这个按钮

alt

call方法

alt

function show(x,y){
    alert(this);
    alert(x + "-" + y);
}
//不用call: show(1,2)
输出结果:object window
        1,2
//用call强制改变this指向后: show("call"m1,2)
输出结果:call
        1,2

apply方法

alt

function show(x,y){
    alert(this);
    alert(x + "-" + y);
}
show.apply("call",[1,2]);

apply使用小技巧

alt

bind方法

预设this指向

alt
alt
输出结果:bind 40,50

三个区别:

alt

箭头函数中注意点和this指向问题

解构