JavaScript 中 this 的指向问题

这篇文章中,我们来研究一下this 的指向问题,在 JavaScript 中this 的指向取决于一个方法是如何被调用的,我们可以根据下面几项来判断 this 到底指向什么。

  • 默认情况,this 在 NodeJS 环境里指向 global对象,而在浏览器里,this 指向 window 对象

function foo () {
    console.log("Simple function call");
    console.log(this === window); 
}

foo();  //prints true on console
console.log(this === window) //Prints true on console.
(function(){
    console.log("Anonymous function invocation");
    console.log(this === window);
})();
// Prints true on console
  • 当一个方法被作为一个对象的一个参数调用时,this 指向此对象
function foo () {
    'use strict';
    console.log("Simple function call")
    console.log(this === window); 
}

let user = {
    count: 10,
    foo: foo,
    foo1: function() {
        console.log(this === window);
    }
}

user.foo()  // Prints false because now “this” refers to user object instead of global object.
let fun1 = user.foo1;
fun1() // Prints true as this method is invoked as a simple function.
  • 当一个方法使用 new 操作符调用,此 this 指向这个新创建的实例

function Person(fn, ln) {
    this.first_name = fn;
    this.last_name = ln;

    this.displayName = function() {
        console.log(`Name: ${this.first_name} ${this.last_name}`);
    }
}

let person = new Person("John", "Reed");
person.displayName();  // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName();  // Prints Name: Paul Adams
  • 当方法用 call 或者 apply 被调用时,this 指向 call 或 apply 函数的第一个参数
function Person(fn, ln) {
    this.first_name = fn;
    this.last_name = ln;

    this.displayName = function() {
        console.log(`Name: ${this.first_name} ${this.last_name}`);
    }
}

let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul Adams

person.displayName.call(person2); // Here we are setting value of this to be person2 object

对学习抱有热情的开发小伙伴欢迎加入 qq群685421881,更欢迎热爱编程的妹子进入,让我们一起学习 并进步吧!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.概念 在JavaScript中,this 是指当前函数中正在执行的上下文环境,因为这门语言拥有四种不同的函数调...
    BluesCurry阅读 4,890评论 0 2
  • 继续说一下面向对象开发。 下面我简单说一下this的指向问题this在js中主要研究的是函数中的this** 表明...
    7月7日晴i阅读 3,474评论 2 8
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 10,206评论 0 5
  • 作者简介:高云起 行到水穷处,坐看云起时。 我会为您精心挑选好书,用笔记分享书的精华。 愿我成为陪伴您一生的读书人...
    三个好妈妈阅读 8,953评论 0 2
  • 善待自己 最近北京太热了,因为空调我们没有感觉到热,可是空调带给我们的不仅仅是凉快,还有身体的寒气。很不...
    源之泉阅读 1,090评论 0 1

友情链接更多精彩内容