关于严格模式下的this指向问题

426 阅读1分钟

1. 在全局作用域中,this 指向window。

'use strict';
console.log(this === window);  // true

2. 在全局作用域中的函数中,this指向undefined。

function foo() {
   console.log(this);
}
foo();   // undefined

3. 对象的方法中

3.1 通过对象调用方法,this指向当前对象。

let bar = {  
    name: 'bar',  
    getName: function(){    
       console.log(this);       // {name: "bar", getName: ƒ}
       console.log(this.name);  // bar
    }
}
bar.getName();

3.2 通过引用调用方法,this指向undefined。

let bar = {  
    name: 'bar',  
    getName: function(){    
       console.log(this);       // undefined
       console.log(this.name);  // TypeError: Cannot read property 'name' of undefined
    }
}
let getName = bar.getName;
getName();

4. 构造函数中的this,指向实例对象。

function Con(name, age) {  
    this.name = name;  
    this.age = age;  
    console.log(this);  // Con {name: "con", age: 3}
}
let con = new Con('con', 3);

5. 事件处理函数中的this,this指向当前节点。

let oBtn = document.getElementById('btn');
oBtn.addEventListener('click', function () {  
    console.log(this);  // <button id="btn">按钮</button>
});

// oBtn.onclick = function() {  
//    console.log(this);   // <button id="btn">按钮</button>
// };

6. 内联事件处理函数中,this指向分为两种形式。

6.1 如果是回调函数中的this,this指向为undefined;

<button id="btn1" onclick="(function() { 'use strict'; console.log(this) })()">按钮1</button>
<button id="btn2" onclick="'use strict'; (function() { console.log(this) })()">按钮2</button>

6.2 如果不在函数中,this指向当前节点。

<button id="btn3" onclick="'use strict'; console.log(this) ">按钮2</button>