JS的this关键字

JavaScript中的this关键字是一个难以琢磨的概念,是一个依赖于它的执行环境而被解析的关键字。

1,在JS文件中直接alert(this);this代表的是window,当前的执行环境是在JS的顶层域里面。

2,下面这个例子中this指向的是调用该方法的对象,button标签。

  1. <script type="text/javascript">
  2. function test() {
  3. alert(this.value);
  4. this.style.color = "red";
  5. }
  6. </script>
  7. </head>
  8. <body>
  9. <input type="button" id="ipt" value="test this">
  10. <script type="text/javascript">
  11. document.getElementById("ipt").onclick = test;
  12. </script>
  13. </body>
  14. </html>
<script type="text/javascript">
	function test() {
		alert(this.value);
		this.style.color = "red";
	}
</script>

</head>
<body>
	<input type="button"  id="ipt" value="test this">
	<script type="text/javascript">
		document.getElementById("ipt").onclick = test;
	</script>
</body>
</html>
上面的例子等价于下面的例子,document.getElementById("ipt").onclick相对于把test函数变成了id为 ipt元素的一个函数属性了,从而让this指向了id为 ipt元素。但是如果写成<input type="button" id="ipt" οnclick="test()" value="test this">这样的方式调用test方法,this却是指向了window。(不明白?直接指定的话没有JS环境绑定?)

  1. <script type="text/javascript">
  2. function test() {
  3. alert(this.value);
  4. this.style.color = "red";
  5. }
  6. </script>
  7. </head>
  8. <body>
  9. <input type="button" id="ipt" value="test this">
  10. <script type="text/javascript">
  11. var button = document.getElementById("ipt");
  12. test.call(button);
  13. </script>
  14. </body>
  15. </html>
<script type="text/javascript">
	function test() {
		alert(this.value);
		this.style.color = "red";
	}
</script>

</head>
<body>
	<input type="button"  id="ipt" value="test this">
	<script type="text/javascript">
		var button = document.getElementById("ipt");
		test.call(button);
	</script>
</body>
</html>
3,在一个函数中,this代表这个函数的执行环境
[javascript] view plain copy print ?
  1. function Test(){
  2. alert(this);
  3. }
  4. Test();//outputs window
  5. var obj = new Test(); // outputs object
function Test(){
	alert(this);
}

Test();//outputs window

var obj = new Test(); // outputs object
Test()是在window域里执行的,其等价于window.Test();
var obj = new Test(); 其相当于 obj.Test();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值