我已阅读关于“this”关键字,并且我了解到“this”关键字适用于上下文中的对象。在JavaScript中使用“this”关键字
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid" required ><input type="submit"></label>
<div><button onclick="previewMessage()">Preview errors</button></div>
<div id="err"></div>
</form>
<script>
function checkValid() {
if (this.value == "fun") {
this.setCustomValidity("You're having too much fun!");
} else {
// input is fine -- reset the error message
this.setCustomValidity('');
}
}
function previewMessage() {
var myform = document.getElementById("noFun")
document.getElementById("err").innerHTML = myform.validationMessage;
}
</script>
</body>
</html>
但是当我使用oninput =“checkValid”,它应该复制checkValid的功能和作用里面的“this”关键字应指向输入object.But这是不是这样的!
看看这段代码,它意味着与前一个相同,但正常运行。
<form id="myForm">
<label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid(this)" required ><input type="submit"></label>
<div><button onclick="previewMessage();">Preview errors</button></div>
<div id="err"></div>
</form>
<script>
function checkValid(input) {
if (input.value == "fun") {
input.setCustomValidity("You're having too much fun!");
} else {
// input is fine -- reset the error message
input.setCustomValidity('');
}
}
function previewMessage() {
var myform = document.getElementById("noFun")
document.getElementById("err").innerHTML=myform.validationMessage;
}
</script>
你能解释一下我的两个片段,以及为什么预期的第一个例子不工作之间的差别。
在此先感谢!
当你调用'checkValid()'时,'this'是'window'。调用它时,您必须执行类似'this.checkValid = checkValid; this.checkValid()'或称它为'checkValid.call(this)'。 – Siguza
可能重复[“这个”关键字如何工作?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –