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

你可能感兴趣的:(Javasript中各种状态下的this指向)