JS 困惑之this的指向

JS中,this到底指向谁,一直是比较困惑的问题,由于this的指向问题造成bug,在程序中经常出现,如何正确理解this的应用,是写好js代码的关键。

案例1:

function thiswindow() {
     console.log(this === window);   //输出为true
}
thiswindow();

我们运行以上代码,发现this指向的是window对象。我们把代码稍作改变如下:

案例2

function thiswindow() {
     console.log(this === window);     //输出为true
     console.log(this);      //输出为thiswindow对象
}
var s = new thiswindow();

以上案例说明,this的指向会随着调用方式的不同发生变化,变化的原则就是,this指向函数的调用这,在第一事例中,函数的调用者是window,第二个实例中,由于使用new创建了一个对象,则函数的调用时这个对象触发,则函数的调用者变成了thiswindow对象本身。

案例3

function thiswindow(msg) {

    this.name = msg;
}
thiswindow.prototype.show = function () {
     console.log(this.name);
}

thiswindow("m1")
console.log(this.name);  //输出m1
var s1 = new thiswindow("s1"); 
var s2 = new thiswindow("s2"); 
s1.show();  //输出s1
s2.show();  //输出s2
s1.show();  //输出s1
console.log(this.name);  //输出m1

通过以上案例,就可以明确知道,调用方式的不同,造成this的指向时不同的,对于thiswindow函数直接调用,this指向的是window,所以两次的直接输出this.name都是m1,对于声明的s1\s2对象来说,器指向的就声明的对象本身,则this指向的是对象本身,并且就算s2改变了name,也不会影响s1对象中的name信息。

对事件和setTimeout等对象,其this指向

案例4

  setTimeout(function() {
    console.log(this === window);   //输出为true
}

案例5

  var btn = document.querySelector("button")
        btn.onclick = function(e) {
        console.log(this);//this的指向是[object HTMLButtonElement]
        console.log(e.target)
}

这个里面this和target有点迷惑性,为什么有了this,还要定义target呢,其实2两者的作用是不一样的,this指向的事件绑定对象,target指定的是事件触发对象。

例子如下:

<div id="ddd">
        <button id="bbb">点击</button>
    </div>
const b = document.querySelector("div");
b.addEventListener("click", function (e) {

    console.log(this);   //输出div
     console.log(e.target); 输出button对象
})

 

posted @ 2022-10-12 11:28  Min.Xiaoshuang  阅读(22)  评论(0编辑  收藏  举报