javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > js this值

JavaScript 中 this 的值如何理解

作者:二叉树果实

文章介绍了JavaScript中this值的5种判断方式,包括函数调用、对象方法调用、构造函数调用、apply/call/bind方法调用和箭头函数中的this,感兴趣的朋友跟随小编一起看看吧

如何解释Javascript中的this值?

在 JavaScript 中,this 的值是动态的,通常会由被使用的函数来决定。所以,影响 this 的值不是定义的时候,关键在于会在哪里被调用。

this 值 5 种判断方式

1.函数调用

当一个函数不是属于一个对象中的方法时,直接作为函数来调用时,this 会指向全局对象,在浏览器中,默认为 Window。但有一点要注意的是,如果是在严格模式下,this 为 undefined。

例子如下,因为是一般函数调用,this 总是指向 Window,所以一个输出结果是 Window。而因为在全局范围中用 var 定义 name 变量。name 变量会绑定在 Window 对象上,第二个输出结果也就等同于 window.name 的值(如果是用 let 定义,并不会绑定在 Window 对象上)

var name = "John";
function callThis() {
  console.log(this);
  console.log(this.name);
}
callThis();
// Window
// John

2.对象方法调用

当一个函数是作为一个对象的方法来调用时,this 会指向这个对象

const john = {
  name: "john",
  callJohn() {
    console.log(`hello, ${this.name}`);
  },
};
john.callJohn(); // hello, john
this 的指向取决于函数被调用的方式,而不是函数定义的位置。 因为使用的时候是 join.xxx,对象调用。

关键反例:

const john = {
  name: "john",
  callJohn() {
    console.log(this.name);
  },
};
const fn = john.callJohn;
fn(); // undefined(或严格模式下报错)

3.构造函数调用

当一个函数使用 new 调用的时候,会出现如下情况

重点来看this 指针的调用

第一处 this 指针

第二处 this 指针

4.apply、call、bind 方法调用

我们也可以使用 applycallbind 方法来指定 this 指向的对象。

举例如下:

function greet(greeting, punctuation) {
  console.log(`${greeting}, I am ${this.name}${punctuation}`);
}
const person = {
  name: "Alice",
};

apply —— 立即执行,参数用数组传

greet.apply(person, ["Hi", "~"]);
//Hi, I am Alice~

call —— 立即执行,参数逐个传

greet.call(person, "Hello", "!");
//Hi, I am Alice~

bind —— 不立即执行,返回一个新函数

const boundGreet = greet.bind(person, "Hey");

此时:

执行返回的新函数:

boundGreet("!!!");
// Hey, I am Alice!!!

补充知识点:

为什么 bind 常用于事件 / 回调? setTimeout(greet.bind(person, "Hello"), 1000);
因为:setTimeout 会丢失原来的 this bind 可以提前把 this 固定住

5.箭头函数中的this

ES6 中介紹了一种新的函数形式 - 箭头函数(arrow function)。但要注意的是,箭头函数并没有属于自己的 this 值,箭头函数的 this 会从他的外层函数继承,若他的外层函数也同为箭头函数 ,則回继续向上找,直到找到全局环境的预设 this 值(例如:浏览器中就是 window)。

let getThis = () => this;
console.log(getThis() === window); // true

到此这篇关于如何解释JavaScript 中 this 的值?的文章就介绍到这了,更多相关js this值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文