JavaScrpit 基础系列之 this 关键词(九)

125 阅读1分钟

this 是什么?

JavaScript this 关键词指的是它所属的对象

它拥有不同的值,具体取决于它的使用位置:

  • 在方法中,this 指的是所有者对象。
  • 单独的情况下,this 指的是全局对象。
  • 在函数中,this 指的是全局对象。
  • 在函数中,严格模式下,this 是 undefined。
  • 在事件中,this 指的是接收事件的元素。

像 call() 和 apply() 这样的方法可以将 this 引用到任何对象。

方法中的 this

在对象方法中,this 是指该方法的拥有者。

var person = {
    name: '张三',
    age: 10,
    getName: function () {
        console.log('name is' + this.name) // name is张三
        console.log(this) // {name: "张三", age: 10, getName: ƒ}
    }
}
person.getName()

单独的 this

单独使用 this 时,拥有者是全局对象 Window

var a = this
console.log(a) // Window {window: Window, self: Window, document: document, name: "", location: Location, …}

函数中的 this

在函数中,函数的拥有者默认绑定 this。因此,在函数中,this 指的是全局对象 Window

function myFuc () {
    console.log(this) // Window {window: Window, self: Window, document: document, name: "", location: Location, …}
}
myFuc()

函数中的严格模式下,this 是未定义的 undefined

"use strict";
function myFuc() {
  console.log(this) // undefined
}
myFuc()

事件中的 this

事件中的 this 是值接收事件的元素。

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