js中this指向

5 阅读1分钟

This指向

  1. html中的this指向

1. this通常只在调用时候确定,与定义位置无关。(箭头函数的this指向定义时确认)。

2. 普通函数中的this指向,默认指向全局对象(非严格windows 严格状态下undefined)。

JavaScript function test() {   console.log(this.num);   } test() //undefined

3. 作为对象方法非箭头函数)时,this指向该对象实例。

a. obj.method() 指向 obj

JavaScript const test = {     a: 3,     fn () {         console.log(this)     } } const a = test.fn() // test

b. obj.method 指向 windows

JavaScript const test = {     a: 3,     fn () {         console.log(this)     } } const a = test.fn a() // windows

c. 对象中的箭头函数继承外部this

JavaScript var obj = {   num: 1,   doTest: () => {     console.log(this)   } }; obj.doTest() // windows  

d. new Method() 指向新创建的实例

JavaScript var obj = {   user: 'yupi',   print: function(){     console.log(this.user);   } } new obj.print()  // undefined

4. call , apply , bind 改变函数方法的 this 指向对象实例。

a. 当 call 等方法接受的对象是 null 或 undefined 时候this指向windows对象。

JavaScript function test() {   console.log(this); } test.call(null); // windows

 

核心口诀

this 看调用,不看定义。谁调用我,this 就是谁。直接调用,this 是全局(或 undefined)。