function里的this指向问题

有时候我会把事件函数里的this当成出发该事件的dom对象,其实不是这样的除非用call和aply去改变this指向,否则this是指向window的

例如下面代码:

<form action="#">
		邮编:<input type="text" name = "" onkeyup = "checkDate(this.value)">
	</form>
	<script>
		function checkDate(value){
			if(value.length > 6){
				alert('邮编长度不能超过六位');
				let textValue = value.slice(0, 6);
				console.log(this);
				this.value = textValue;
			}
		}
	</script>

结果为:


但如果用call改变this情况就不一样了,this会指向触发该事件的dom对象

<form action="#">
		邮编:<input type="text" name = "" onkeyup = "checkDate.call(this,this.value)">
	</form>
	<script>
		function checkDate(value){
			if(value.length > 6){
				alert('邮编长度不能超过六位');
				let textValue = value.slice(0, 6);
				console.log(this);
				this.value = textValue;
			}
		}
	</script>


猜你喜欢

转载自blog.csdn.net/dreamjay1997/article/details/80618006