浅谈JavaScript中this指向的⼏种情况

总结JavaScript中this指向的⼏种情况,同时来看⼀下如何对this的指向进⾏修改
       如果是在对象⾥⾯使⽤this,⼀般来讲,关键字this是指它所在的对象。this可以⽤在⽅法内,获取对对象属性的访问。

this指向的⼏种情况:

          1、 默认指向: this默认指向的是window对象。

// 默认指向
    console.log(this);

          2、 函数调用时:

                ① 独立调用 this时: 指向 window对象

//  独立调用的时候 (谁调用函数,this就指向谁)
 function test(){

         console.log(this);
 }

test();

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

// 函数作为对象的方法调用的时, this指向当前对象

 let obj = {
      name:"test",
      show:function(){

          console.log(this);

          console.log(this.name);
      }
 }

 obj.show(); //打印:test

//注意:下面代码是调用是:this指window对象
      let a = obj.show;

      a();

          3 、指向当前对象

 

//指向当前对象

 let obj = {
    name:'test',
    age:19,
    show:function(){
         console.log(this);
         console.log(this.name,this.age)
      
         this.sayhello();
    },sayhello:function(){
console.log(
"hello");
}
} obj.show();//打印:test 19 obj.sayhello();//打印:hello

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

                对this的指向进⾏修改:1、call()

                      2、apply()

                      3、bind()

// 改变this的指向,可以使用函数提供的call()和apply(),还有es5中bind()
    let obj={
        name:"hello",
            age:19,
            show:function(x,y){
                console.log(this);
                console.log(this.name);
                console.log(this.age+x+y);
        }
    }

    let obj2={
        name:"张三",
        age:30
    }
     obj.show(10,20);//打印:hello   49
//call()
obj.show.call(obj2,10,10);//打印:张三 50
//apply()
obj.show.apply(obj2,[10,20]);//打印:张三 60
//es5中bind() let test =obj.show.bind(obj2);
test(10,30);//打印:张三 70
//箭头函数的this的指向:它的this指向始终是指向外层作用域

document.querySelector("button").onclick=()=>{
  console.log(this);
}
let obj = {
    name:"test",
    show:()=>{
        console.log(this);//由于i为⼀个箭头函数,所以this是指向外层的,所以this.name将会打印出test
} } obj.show();//打印:test

 

 
 
 
 
 this指向当前对象

 

原文地址:https://www.cnblogs.com/suger-4/p/12567714.html