关于JavaScript中的this指向问题

        /*e.target与this区别 e.target点击了哪个元素,就返回那个元素...
        this返回的是绑定事件的对象(元素) */
        //this指向问题 一般情况下this的最终指向的是那个调用它的对象
        //1.全局作用域或者普通函数中this指向全局对象window(定时器里面的this指向window)
        //注意:如果函数是独立调用,那this指向是undefined,但是在非严格模式下,当this指向undefined时,它会被自动指向window
        console.log(this);
        function fn() {
            console.log(this);
        }
        window.fn();//相当于window.fn();
        window.setTimeout(function () {//由于定时器是window调用
            console.log(this);
        }, 1000);
        //2.方法调用中谁调用this指向谁
        var n = {
            pps: function () {
                console.log(this);//this指向的是n这个对象
            }
        }
        n.pps();
        var btn = document.querySelector("button");
        btn.addEventListener("click", function () {
            console.log(this);//this指向的是btn这个按钮对象
        })
        //btn.οnclick=function(){
        //     console.log(this); this指向的是btn这个按钮对象
        // }
        //3.构造函数中this指向构造函数的实例
        function fn() {
            console.log(this);//this指向的是fn 实例对象            
        }
        var fun = new fn();
        //4.如果函数是独立调用,那this指向是undefined,但是在非严格模式下,当this指向undefined时,它会被自动指向window
         function fn() {
            "use strict"
            console.log(this);//undefined
        }
        fn();

ES6箭头函数的this

**为什么出现箭头函数this
解决了匿名函数this指向的问题
setTimeout和setInterval中使用this造成的问题
箭头函数中的this
箭头函数没有自己的this,而且箭头函数的this不是调用的时候决定的,
而是定义时所处的对象就是它的this
(箭头函数的this看外层是否有函数,如果有,外层函数的this就是内部箭头函数的this,如果没有,this就是window)
**

//ES5与ES6中的this对比
btn1.onclick=function(){
console.log(this);//btn1
}

btn2.onclick=()=>{
console.log(this);//window
}

let obj = {
            name: "tom",
            getName: function () {//由于普通函数有自己的this,所以this是obj
                btn2.onclick = () => {
                    console.log(this);//obj
                }
            }
        }
        obj.getName();

let obj = {
            name: "tom",
            getName:()=> {
                btn2.onclick = () => {
                    console.log(this);//window
                }
            }
        }
        obj.getName();
发布了22 篇原创文章 · 获赞 26 · 访问量 628

猜你喜欢

转载自blog.csdn.net/HwH66998/article/details/103551313