在JavaScript中使用“this”关键字
我已阅读关于“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>
你能解释一下我的两个片段,以及为什么预期的第一个例子不工作之间的差别。
在此先感谢!
但是,当我使用oninput =“checkValid”时,它应该复制checkValid函数,并且函数内的“this”关键字应指向输入对象。
不,不应该。
内部事件属性的值是事件处理函数的主体。
的HTML oninput="checkValid"
等同于JavaScript的:
reference_to_input.oninput = function (event) {
checkValue;
};
一提的变量(如checkValue
),而不做任何它(就像把()
后调用一个函数)什么都不做。
您设置事件处理程序的方式是这样的:this
的值将是而不是是<input>
元素。你有什么相当于一个“裸体”函数调用,所以this
将引用window
对象。
但是,如果你要建立该事件处理程序在JavaScript这样的:
document.getElementById("noFun").oninput = checkValid;
你会得到this
参考元素。
请注意,您的代码将将引用传递给元素作为参数,这就是您的第二个代码示例的作用原因。
那么有什么区别 –
document.getElementById (“noFun”)。oninput = checkValid; –
AND
当你调用'checkValid()'时,'this'是'window'。调用它时,您必须执行类似'this.checkValid = checkValid; this.checkValid()'或称它为'checkValid.call(this)'。 – Siguza
可能重复[“这个”关键字如何工作?](http://*.com/questions/3127429/how-does-the-this-keyword-work) –