this 指向

一、全局 this 指向

全局 this 指向取决于环境,在浏览器环境中 this 指向 window,在 node 环境中 this 指向空对象。

二、函数 this 指向

1. 箭头函数

箭头函数没有 this。箭头函数定义的位置 this 指向谁,箭头函数里面的 this 就指向谁。

2. 普通函数

this 指向取决于怎么调用的。

2.1 通过 new 调用

this 指向实例对象

new Method();

2.2 直接调用

this 指向全局对象

method();

2.3 通过对象调用

this 指向对象

obj.method();

2.4 call、apply、bind

this 指向第一个参数

method.call(obj);

你可能感兴趣的:(javascript)