我已閱讀關於「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) –