You don't have javascript enabled. Good luck! :(

欢迎页

Welcome to Ganace's Blog


欢迎您来到Ganace 的个人博客。

在茫茫互联网的海洋里能够遇见,实在是一份不小的幸运。

诚挚地向您问候一声:您好,朋友!

这里是属于Ganace个人的隐秘小空间,记录了工作学习中遇到的知识点与灵感,以及生活中的碎碎念与吐槽突如其来的中二病尬尬的文艺时间锻炼腹肌的时刻惊喜的小发现等等。

想要在自己的平淡无奇的人生长河中留下些什么,

或者只是为了拯救老人家岌岌可危的记忆力,

仅此而已。

来到此地,分享与你。

也期待与您的再次相遇!

Share with Me


有任何的分享或者建议与吐槽,都可以Email我:ganace@foxmail.com

欢迎您的来信!

【JavaScript】JavaScript中this关键字的用法

  Sep 12, 2020     Ganace     Front-end-Foundation

JavaScript

复习一下JavaScript中this关键字的用法。


this不同情况下的区分

  • 在对象方法中, this 指向调用它所在方法的对象。

  • 单独使用 this,则它指向全局对象(浏览器中为window)。

  • 函数中使用 this,this 指向函数的所属者(浏览器中为window)。

  • 严格模式下,函数中使用 this,this 为 undefined。

  • 在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素。


方法中的 this

在对象方法中, this 指向调用它所在方法的对象。

例下:this指向obj对象

var name = '企鹅', friend = '豆豆';
var obj = {
  name: '森碟',
  rest: function () {
    console.log(this.name + '吃饭' + '睡觉');
  },
  exercise: function() {
    console.log(this.name + '' + this.friend);
  }
}
obj.rest(); //森碟吃饭睡觉
obj.exercise();//森碟打undefined

rest方法、exercise 方法所属的对象就是 obj。

单独使用 this

单独使用 this,则它指向全局(Global)对象。

在浏览器中,window 就是该全局对象,为 [object Window]。,

var obj = this;
console.log(this);//Window {parent: Window, ...}

严格模式下,单独使用 this,也一样指向全局(Global)对象。

"use strict";
var obj = this;
console.log(this);//Window {parent: Window, ...}

函数中使用 this

默认情况下,函数的所属者绑定在 this 上。

默认情况下,函数中使用 this,this表示全局对象,window 就是该全局对象。

function getThis() {
  console.log(this);
}
getThis();// Window {parent: Window, ...}

严格模式下,函数的所属者没有绑定在 this 上。

严格模式下,函数中使用 this,this 为 undefined。

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

事件中的 this

在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素

<button onclick="this.style.color='red'">
  点击变红色
</button>