Javasript中各种状态下的this指向

据我所知的有5种:
1.作为普通函数调用:this指向全局
2.作为对象的方法调用:this指向当前对象
3.作为构造器使用: this指向实例对象
4.用call、apply调用时:this指向所指定的上下文
5.在箭头函数中使用this时:this指向箭头函数开始定义的上下文

作为普通函数调用

function test () {
    return this;
}
function test2 () {
    console.log(test());
}
let obj = {
    test: function() {
        console.log(test());
    }
}
console.log(test()); // window
test2(); // window
obj.test(); //window

作为对象的方法调用

let obj = {
    test: function() {
        return this;
    }
}
console.log(Object.is(obj, obj.test())); // true

作为构造函数调用

function Fn (num) {
    this.age = num;
}
let fn = new Fn(10);
let fn2 = new Fn(11);
console.log(fn.age); // 10
console.log(fn2.age); // 11

使用call、apply调用

window.str = 'window';
let obj = {
    str: 'obj',
}
function test () {
    test.str = 'test';
    console.log(this.str);
}
test(); // 普通调用,this执行window, 输出window
test.call(obj); // obj
test.call(test); // test

箭头函数的this

var fn = () => this; // 在全局下定义
function test () {  // 在全局下定义
    return this;
}
let obj = {
    fn: fn,  // 在obj对象中使用
    test: test,  // 在obj对象中使用
}
console.log(Object.is(obj.fn(), window)); // true
console.log(Object.is(obj.test(), obj)); // true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. this之谜 在JavaScript中,this是当前执行函数的上下文。因为JavaScript有4种不同的...
    百里少龙阅读 1,033评论 0 3
  • 葡萄藤PPT JS中this的指向 大家好,我是IT修真院郑州分院第6期的学员王栋,一枚正直、纯洁、善良的前端程序...
    17064阅读 634评论 0 2
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,665评论 0 5
  • 新手在入门 JavaScript 的过程中,一定会踩很多关于 this 的坑,出现问题的本质就是 this 指针的...
    一缕殇流化隐半边冰霜阅读 3,835评论 15 47
  • 与其他语言相比,函数的this关键字在JavaScript中的表现略有不同,此外,在严格模式和非严格模式之间也会有...
    codingC阅读 587评论 0 0