JavaScript This

This

JavaScript 的 This 会指向不同的对象,这依据函数如何被呼叫的。
当函数被呼叫,形成新的执行环境,而每个执行环境有自己的变数环境
(Variable Environment),也就是被创造在函数的变数所在。如果找不到函数里面变数的参考,它会到外面找,直到全域环境(global)为止。

JavaScript 的This 如果是在物件的函数中,那麽这个this指的是调用这个方法的对象
EX:

var person = {
  firstName: "Ivy",
  lastName : "Huang",
  id : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName()); //Ivy Huang

这里的this 指的是 person这个物件,因为person调用了它自己的方法 —— fullName。

知道了这个概念,我们可以利用物件方法的 this 来改变此物件的属性
EX:

var person = {
firstName: "Ivy",
  lastName : "Huang",
  id : 5566,
    changeName : function(newName){
    this.firstName = newName;
    }
};

person.changeName('Lisa');
console.log(person.firstName);//Lisa


如果只是纯粹呼叫函数呢?
EX:

function a (){
console.log(this);

}
a(); // window

var b = function(){
  console.log(this);
}
b(); //window

也是指向同一个物件,window。

console.log(this)
//VM149:1 Window {0: global, 1: global, 2: global, 3: Window, 4: Window, 5: global, window: //Window, self: Window, document: document, name: '', location: Location, …}

这里的this指的是全域物件,在浏览器里面是window这个物件。

小提醒:在物件里面的箭头函式的this指的是window 物件!

EX:

var person = {
name: 'Ivy',
age:20,

callName: ()=>{
console.log(this.name)
},
}

person.callName();//undifined

因为这个callName的this指的是window 物件。

菜鸟教程


<<:  那些被忽略但很好用的 Web API / History

>>:  如何用 AppFollow 做关键字研究

[day-28] Python-实战应用-Line讯息传送

实战应用篇P1   这次我们要使用的是Line Notify当作我们的讯息传播方式,Line Not...

[Day11] 2D的数学世界 (三) - 位移、旋转、缩放

今日目标 位移、旋转、缩放 以下位移、旋转、缩放仅是补充,又或着是说个人笔记(?),阅读这篇单纯的看...

[Day9] Review and Supplement by use Leetcode problem

到今天也已经是第 9 天了,讲了颇多东西但是可能没有这麽完整或明确,所以这篇主要拿来复习之前的内容。...

Day_12 : 让 Vite 来开启你的Vue 之 来!开始你的 Vue 3

Hi Dai Gei Ho~ 我是Winnie~ 进入Vue章节前的 温腥提醒: 在之後的文章中,预...

浅谈传输层协定(一):TCP 在做什麽?

前面提到 TCP/IP 模型,TCP 和 IP 两个协定可说是现今网路架构的最重要的协定之二。 TC...