我对JS中'this'的使用感到困惑。
以w3cshool为例: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onchange2
<!DOCTYPE html>
<html>
<body>
<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p>
Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">
<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val);
}
</script>
</body>
</html>
如果我删除'this',它也有效,太糟糕了我在w3school找不到任何教程来区分它。
在什么情况下'这个'会与不是'这个'有所不同?
答案 0 :(得分:0)
&#34;这&#34;指的是函数的当前上下文或您使用它的方法。因此在您的示例中,这是指输入元素,因为您输入的内容的值是从onchange事件输入的,因此&#34 ; THIS.VALUE&#34;将返回您输入的任何内容。这是一个相关的stackoverflow问题,它有一个很好的答案:What does "this" mean?
答案 1 :(得分:0)
到目前为止,您可以理解,当事件处理程序分配给元素时,this
可以隐式/显式地使用。
但是该示例试图强调甚至整个对象this
都可用并且可以传递给事件处理程序的事实。看看下面修改过的代码:
<!DOCTYPE html>
<html>
<body>
<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p>
Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this)">
<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val.value);
alert("The input value has changed. The new value is: " + val.type);
}
</script>
</body>
</html>
&#13;
答案 2 :(得分:0)
为on****
HTML属性定义的代码没有区别。该代码可以访问为this
对象的每个属性定义的别名,因此您可以省略this.
。这仅适用于直接分配给on
属性的代码。这些别名将不再存在于您可能从那里调用的函数中。
演示:
<div onclick="textContent='you clicked!';console.log(textContent)">click me</div>