0
点赞
收藏
分享

微信扫一扫

JavaScript|this


JavaScript|this

1.在方法中

在方法中,this关键字指向的是当前方法所属的对象:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this</title>
<script>var personName = {
firstName:"",
lastName:"",
displayName : function (){
// 方法中this指向该方法所属对象
document.getElementById("p1").innerHTML = this.firstName + this.lastName;
}
}
function Make(){
// 把personName这个对象的值从新修改了过后再调用它的方法
personName.firstName = document.getElementById("input1").value;
personName.lastName = document.getElementById("input2").value;
personName.displayName();
}</script>
</head>
<body>

请输入你的姓:
<input type="text" id="input1">
<br>
请输入你的名:
<input type="text" id="input2">
<br>
<button onclick="Make()">显示</button>
<p id="p1" style="display:">你的姓名</p>

</body>
</html>

JavaScript|this_this


JavaScript|this_全局对象_02

2.object Window

在单独使用this,或者在非类中的函数使用this,都是指向window的,也就是全局对象object Window。

在严格模式下非类中的函数使用this是undefined。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this</title>
</head>
<body>

<p id="p1"></p>
<p id="p2"></p>
<script>// 单独使用this指向全局对象,即object Window
document.getElementById("p1").innerHTML = this;
// 非对象的函数中默认this指向全局对象,即object Window
document.getElementById("p2").innerHTML = Fun();
function Fun(){
return this;
}</script>

</body>
</html>

JavaScript|this_this_03

3.事件中的this

事件中的this指向了接收事件的HTML元素:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this</title>
</head>
<body>

<button onclick="Fun(this)">点击消失</button>
<script>function Fun(x){
// 事件中this指向接受事件的元素
x.style.display = "none";
}</script>

</body>
</html>

JavaScript|this_javascript_04

点击按钮,按钮就会消失

人生没有白走的路,每一步都算数!


举报

相关推荐

0 条评论