JavaScript this 关键字

作者: Kevin_hoo | 来源:发表于2021-01-14 17:38 被阅读0次

前言

面向对象语言中 this 表示当前对象的一个引用。
但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

  • 如果单独使用,this 表示全局对象。
  • 在方法中,this 表示该方法所属的对象。
  • 在函数中,this 表示全局对象;但严格模式下,this 是未定义的(undefined)。
  • 在事件中,this 表示接收事件的元素。
  • 类似 apply(),bind()和call()方法可以将 this 引用到任何对象。

看了很多资料,基本上都让大家坚持一个原理:this 永远指向最后调用它的那个对象。那我们就看一下实际例子吧。

单独使用/全局(参考:globalThis 对象

console.log(this, globalThis) // window

"use strict";
console.log(this, globalThis) // window,严格模式下,this也是指向全局(Global)对象

方法中的 this

// 创建一个对象
var person = {
  firstName: "John",
  lastName : "Doe",
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
person.fullName(); // "John Doe"
window.person.fullName(); // "John Doe"

fullName 是对象 person 调用的,所以打印的值就是 person 中的值。
this 永远指向最后调用它的那个对象”,最后调用它的对象仍然是对象fullName。
⚠️ 注意陷阱

var firstName = 'wang';
var lastName = 'qiang';
var person = {
  firstName: "John",
  lastName : "Doe",
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
var c = person.fullName;
c();

fullName() 最后仍然是被 window 调用的。所以 this 指向的也就是 window。打印结果为:"wang qiang"

函数中使用 this

// 默认
function myFunction() {
  return this;
}
 myFunction() // this 表示 myFunction 函数的所有者

// 严格模式
"use strict";
function myFunction() {
  return this;
}
 myFunction() // undefined

函数中,默认情况下,this 指向全局对象。
严格模式下,this 为 undefined,因为严格模式下不允许默认绑定

事件中的 this(参考runoob

<button onclick="this.style.display = 'none'">点我后我就消失了</button>
<button @click="$event.target.style.display = 'none'">点击消失</button> // Vue写法

<button onclick="myFunction(this)">点我后我就消失了</button>
<script>
function myFunction(t) {
  console.log(t) // <button onclick="this.style.display='none'">点我后我就消失</button>
}
</script>

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

改变 this 的指向

  • 显式函数绑定
var obj = {
  name: "小明",
  select: "芝芝芒芒",
  myFun: function() {
    console.log(
      this.name + "选择" + this.select
    );
  }
};
var db = {
  name: "大江",
  select: "杨枝甘露酸奶"
};
obj.myFun();  // 小明选择芝芝芒芒
// 大江选择杨枝甘露酸奶
obj.myFun.apply(db);
obj.myFun.bind(db)();
obj.myFun.call(db);

bind 返回的是一个新的函数,必须调用它才会被执行。
对比一下call 、bind 、 apply 传参情况:

var obj = {
  name: "小明",
  select: "芝芝芒芒",
  myFun: function(m,n) {
    console.log(
      this.name + "选择" + this.select + "加" + m + "加" + n
    ); 
  }
};
var db = {
  name: "大江",
  select: "杨枝甘露酸奶"
};
obj.myFun.apply(db, ["椰果", "珍珠"]); // 大江选择杨枝甘露酸奶加椰果加珍珠
obj.myFun.bind(db, "椰果", "珍珠")(); // 大江选择杨枝甘露酸奶加椰果加珍珠
obj.myFun.bind(db, ["椰果", "珍珠"])(); // 大江选择杨枝甘露酸奶加椰果,珍珠加undefined
obj.myFun.call(db, "椰果", "珍珠"); //大江选择杨枝甘露酸奶加椰果加珍珠

a-b-c:
第一个参数都是 this 的指向对象。
apply 的所有参数都必须放在一个数组里面。
bind 除了返回是函数以外,它的参数和 call 一样。
call 的参数全都用逗号分隔。
三者的参数不限定是 string 类型,允许是各种类型,包括函数 、 object 等等!

  • 在函数内部使用 _this = this
var name = "kevin";
var a = {
  name : "tom",
  func1: function () {
    console.log(this.name)     
  },
  func2: function () {
    var _this = this;
    setTimeout( function() {
      _this.func1()
    }, 1000);
  }
};
a.func2() // tom
  • 箭头函数
var name = "kevin";
var a = {
  name : "tom",
  func1: function () {
    console.log(this.name)     
  },
  func2: function () {
    var _this = this;
    setTimeout(() => {
    _this.func1()
    }, 1000);
  }
};
a.func2() // tom

⚠️ 箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
⚠️ 如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined。
(参考:ECMAScript 6 入门 > 箭头函数

  • 构造函数
function Foo() {}
Foo.prototype.getName = function(){
  console.log(this.name);
}

var bar = new Foo();
bar.name = 'alex';
bar.getName(); // this 指向实例 bar

再看几个例子

🌰

var a = 10;
var obj = {
  a: 20
}
function myFun(){
  console.log('myFun this:', this);
  function foo(){
    console.log("foo this:", this.a)
  }
  foo();
}
myFun();
myFun.call(obj);

无论fn如何调用,foo都是独立调用,所以foo内部的this都是指向undefined,由于是非严格模式下(默认),因此自动指向window

🌰🌰

'use strict';
var a = 10;
function foo(){
  var a = 1;
  var obj = {
    a:20,
    c: this.a + 20
  }
  return obj.c;
}

console.log(window.foo()); // 30
console.log(foo()); // Uncaught TypeError:Cannot read property 'a' of undefined

参考:
掘金技术社区:
JavaScript中详解this
this、apply、call、bind

相关文章

网友评论

    本文标题:JavaScript this 关键字

    本文链接:https://www.haomeiwen.com/subject/psbuaktx.html