This question already has answers here:
How does the “this” keyword work?
                                
                                    (22个答案)
                                
                        
                2年前关闭。
            
        

据我了解,JavaScript中的“ this”应表示一个调用它的对象,对吗?在下面的示例代码中,“ this”是什么意思?
    `
    
    

<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>

</body>
</html>`

最佳答案

在这里this表示XMLHttpRequest对象,在这里xhttp。但是this的值可以根据上下文而有所不同。在任何函数之外的全局执行上下文中,this指向javascript中的window对象。

检查此链接以获取更多参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

关于javascript - 在此代码示例中,“this”到底是什么意思? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46884164/

10-11 00:41