箭头函数中的this和ES6之前函数中的this指向对比

1 ES6中this的指向是向外层寻找离自己最近的this指向。
在不改变this指向时,箭头函数中this有两种情况

  1. 1 this 指向被注册的元素
<script> 
    var btn=document.querySelector(button);
    btn.onclick=function(){
        console.log(this);//this 指向btn
    }
</script>
  1. 2this 指向window,在对象中,数组对象中,函数中,箭头函数中的this都指向window。此时函数的最外层是全局
  // 1 对象中的箭头函数的this指向window
    var obj = {
        name: 'lxf',
        say: () => {
            console.log(this);
            console.log('对象中箭头函数中的this' + this);
        }
    }
     obj.say();


 // 2 函数中的箭头函数中的this指向window
    function fun() {
        let a = () => {
            console.log('函数中 箭头函数中的this:' + this);
        }
        a(); //调用箭头函数
    }
    fun();


// 3 数组对象中的 箭头函数中的this指向window
    var arr1 = [{
        name: 'age',
        say: () => {
            console.log('函数中的箭头函数中的this'+this);
        }
    }]
    arr1[0].say();

2不改变this指向时, 传统函数中的this指向也有两种情况

  1. 指向实例对象
// 创建对象时this的指向
 function Start(a, b, c) {
        this.uname = a;
        this.age = b;
        this.sex = c;
        this.say = function() {
            console.log(this); //此时的this指向实例对象,
        }
    }
    var ldh = new Start('ldh', 18, 'man');
    ldh.say(); //在此this指向ldh这个对象
  1. 指向调用者
var obj = {
        uname: 'deng',
        age: 18,
        sex: 'man',
        say: function() {
            console.log(this);
        }
    }
    obj.say(); //this指向obj,是obj调用的。

<script> 
    var btn=document.querySelector(button);
    btn.onclick=function(){
        console.log(this);//this 指向btn
    }
</script>
发布了17 篇原创文章 · 获赞 0 · 访问量 428

猜你喜欢

转载自blog.csdn.net/weixin_44805161/article/details/101220330