场景1、 函数直接调用时
- this指向全局变量,node就是global,js就是window
- 严格模式下就是undefined ```javascript // eg one 普通调用 function test () { console.log(this) } test() ; // undefined 或 Window(Object)
// eg two 普通函数调用嵌套一层普通函数调用 function son () { console.log(this) } function father () { son(); } father(); // undefined 或 Window(Object)
<a name="ketXe"></a>## 场景2、 函数被其他对象调用时候- 就是`obj.fun()`被谁点了,this就是指向谁,要注意是**执行的时候**,不是定义的时候- 操作访问符访问方法时,方法会隐式绑定前面的对象```javascript// eg one 正常一个对象里面的函数const father = {type: 'person',buy: function() {console.log(this)}}father.buy(); // {type: 'person', buy: ƒ}// eg two 对象嵌套里面的函数const father = {type: 'person',cat: {type: 'animal',buy: function() {console.log(this)}}}father.cat.buy(); //{type: 'animal', buy: ƒ}// eg three 监听的函数const father = {buy: function() {console.log(this)}}window.addEventListener('scroll', father.buy); // undefined 或 Window(Object), 因为执行的时候是自然执行的//eg four 奇怪的语法const father = {buy: function() {console.log(this)}}(1, father.buy)(); // undefined 或 Window(Object), 因为执行的时候是自然执行的
- 一个额外语法: var a = (1, 2); 这里括号里面会返回第二个值
场景3、 new一个实例的时候
- 就是指向new出来的实例 ```javascript // eg one function Person(aa) { console.log(this) } let teacher = new Person(‘aa’); // Person {} 这里会打印出构造函数,实际上this就是指向新实例的,可以参考可以new过程发生的事情
// new的过程 // 1. 在内存中创建一个新的对象 // 2. 把这个对象的prototype指向这个构造函数的prototype // 3. 然后把这个this指向新对象的this // 4. 然后执行里面的代码赋值 // 5. 如果return非空对象,则正常return;如果没有return,则返回新创建的这个对象
<a name="v5iJP"></a>## 场景4、call,apply,bind- call,apply- 改变this的指向,接受两个参数,一个是this的指向,一个是接受参数- 绑定了函数的this之后立刻执行```javascriptconst obj = {name: 'one'}function test (first, second) {console.log(first, second);console.log(this)}test.call(obj, 1, 2); // 1 2 {name: 'one'}test.apply(obj, [1, 2]); // 1 2 {name: 'one'}
- bind
- 给你返回一个绑定了this的函数
- bind直接传参不能动态传参 ```javascript // eg one const obj = {name: ‘one’} function test (first, second) { console.log(this) } const fun = test.bind(obj, 1, 2); fun(); // 1 2 {name: ‘one’}
<a name="iHX28"></a>## 场景5、箭头函数- this指向离我的**定义时候非箭头函数的上下文**```javascript// eg onefunction one () {console.log(this); // {name: 'test', one: ƒ}// one才是arrow的定义时上下文const arrow = () => {console.log(this)} // {name: 'test', one: ƒ}function two () {console.log(this); // Windowarrow();}two();}const test = {name: 'test'};test.one = one;test.one();// eg twoconst arrow = () => {console.log(this)};const obj = {name: 'joe'};arrow.call(obj); // window
