javaScript中的this
直接po截图和代码
谁调用的,那this就代表谁
以下是一小部分案例,this的内容不止这些,最近事情太多太杂,后面有时间的话,我会再补充一些。
运行效果如下图:
下面是案例的源代码,testJavaScriptThis.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试javascript中的this关键字</title>
<script type="text/javascript">
//测试js中的this
function testThis1(myParameter){
console.log(myParameter);
console.log(myParameter.value);
}
function testThis2(myParameter){
console.log(myParameter);
console.log(myParameter.value);
}
/*
谁调用的,那this就代表谁
我们在调用testThis3()函数时,一般就是直接通过函数名来调用的,比如onclick="testThis3()"这样写,其
实testThis3()函数默认是属于window对象的,所以其实我们可以写成onclick="window.testThis3()",但
是我们一般都喜欢把window省略掉,所以就变成了onclick="testThis3()",所以此时,testThis3()函数中的this表
示window对象
*/
function testThis3(){
console.log(this);
console.log(this.value);
}
var hometown = "江西省赣州市于都县";
//下面这2行代码的效果是一样的
console.log(hometown);
//window其实可以省略不写
console.log(window.hometown);
</script>
</head>
<body>
<input type="text" value="666" onclick="testThis1(this)">
<br/>
<input type="button" value="测试js中的this" onclick="testThis2(this)">
<br/>
<input type="button" value="测试js中的this" onclick="testThis3()">
<br/>
<input type="button" value="测试js中的this关键字" onclick="window.testThis3()">
<br/>
</body>
</html>