js中this是什么?this的5种用法

概述:
1.在方法中,this指的是所有者对象。
2.单独的情况下,this指的是全局对象。
3.在函数中,this指的是全局对象。
4.在函数中,严格模式下,this指的是undefined。
5.在事件中,this指的是接收事件的元素。
**

分述:
**

1.方法中的this
在对象方法中,this指的是此方法的“拥有者”。
this代表person对象

 var person = {
            firstName:"Bill",
            lastName:"Gates",
            id:678,
            fullName:function(){
                return this.firstName + " " + this.lastName;
            }
        };

2.单独的this

(1)在单独使用时,拥有者是全局对象,this指的是全局对象
在浏览器窗口中,全局对象是[object Window]:

 var x = this;
 document.getElementById("demo").innerHTML = x;

(2)在严格模式中,如果单独使用,那么this指的是全局对象[object Window]:

"use strict";
var x = this;

3.函数中的this(默认)

在js函数中,函数的拥有者默认绑定this.
因此,在函数中,this指的是全局对象[object Window]

function myFunction(){
    return this;
    }

4.函数中的this(严格模式)

js严格模式不允许默认绑定,因此,在函数中使用时,在严格模式下,this是未定义的undefined

“use strict”;
function myFunction(){
    return this;
}

5.事件处理程序中的this

this指的是html元素,如下面例子中,this指的是button

<button onclick = "this.style.display='none'">
     点击来删除我!
</button>

 

posted @ 2022-12-03 17:12  net-sky  阅读(1619)  评论(0编辑  收藏  举报