面对对象中改this方法

改this的方法:

1)通过`bind`方法
function func(){
    console.log("func:",this);//指向全局
};
//1:通过bind方法改变this的指向
func.bind({name:"chang this"})();//指向{name:"chang"}这个函数




2:通过call/apply方法
    function func(a,b){
    console.log("func:",this);
};
func.call({name:"change this"},写传参数100,200)//第一个参数传的是改变this的对象,第二个参数传的是参数列表
func.apply({name:"changge this"},通过数组写传参数[100,200])


3:在箭头函数中this指向和外层this指向一样,如果没有外层,就指向全局

let obj={
    show:function(){
    console.log('show',this);//指向show
    (() =>{
        console.log("inner show:",this);//箭头函数的上层指向哪里,箭头函数的this就指向哪里
            })()
        }

    }
    obj.show();

猜你喜欢

转载自www.cnblogs.com/zhangyonghan/p/9163819.html
今日推荐