> 文档中心 > 对JavaScript中 this 关键词的理解

对JavaScript中 this 关键词的理解

目录

  • 理解 this 关键词
  • 具体实践
    • 函数内部
    • 在方法内部
    • 在事件中
    • 箭头函数内

理解 this 关键词

自从我开始学习和使用 JavaScript 以来,就有一件事一直困扰着我,那就是 this 关键字。

当我开始学习 Vue 时,this 给我带来了恶梦。我花了很多时间去学习和实践,今天我将和大家分享我对 this 关键词的一些理解。

this 是面向对象语言的重要组成部分,但是JavaScript中的 this 与Java中的 this 关键字,还有Python中的 self 是不同的! JavaScript 中 this 指的是上下文中的对象,也就是说在函数中,this 指的是包含它的对象,this 的值取决于它的使用方式。

应用场景以及 this 的值有以下几种情况:

  • 默认情况thisglobal对象,即全局对象,指的是 window

  • 函数里thisglobal对象,和默认情况是一样的,但是在 严格 (strict)模式下,this 的值是 undefined

  • 方法内部this指的是所有者对象。(它是属于对象属性的函数)

  • 事件中this指的是触发事件的元素。

  • 箭头函数内部:使用箭头()=>定义函数时,它不会创造 this,而是一直引用它在函数外部引用的同一个对象。

具体实践

下面我们来看具体实践

函数内部

默认则是 window 对象

function test(){    console.log(this)}test();

对JavaScript中 this 关键词的理解

在严格模式下则为 undefined

function test(){    "use strict";    console.log(this)}test();

对JavaScript中 this 关键词的理解

在方法内部

在方法内部 this 指的是在方法调用其中拥有该方法的对象。

const me = {  name: "我想养只猫",  show() {    console.log(this.name);  },  info: {    webSite: "uiuing.com",    show() {      console.log(this.webSite)      }  }};me.show();me.info.show();

对JavaScript中 this 关键词的理解

在事件中

在事件中 this 则是这个dom对象,这个不需要多说,运行一下这段代码就自然知道了。

<body>    <button onclick="run(this)"> CLICK ME!</button>    <script> function run(data){     console.log(data); }    </script></body>

对JavaScript中 this 关键词的理解

在箭头函数内

function 定义函数和 箭头函数的区别在使用 this 时格外明显,具体如下

<body>    <button id="btn"> CLICK ME!</button>    <script> let btn_el = document.getElementById("btn"); btn_el.onclick =  function (){     console.log("function 下的this:",this); }; btn_el.click(); btn_el.onclick = ()=>{     console.log("箭头函数下的this:",this); }; btn_el.click();    </script></body>

对JavaScript中 this 关键词的理解

你能发现区别吗?