1. 在全局作用域中,this 指向window。
'use strict';
console.log(this === window);
2. 在全局作用域中的函数中,this指向undefined。
function foo() {
console.log(this);
}
foo();
3. 对象的方法中
3.1 通过对象调用方法,this指向当前对象。
let bar = {
name: 'bar',
getName: function(){
console.log(this);
console.log(this.name);
}
}
bar.getName();
3.2 通过引用调用方法,this指向undefined。
let bar = {
name: 'bar',
getName: function(){
console.log(this);
console.log(this.name);
}
}
let getName = bar.getName;
getName();
4. 构造函数中的this,指向实例对象。
function Con(name, age) {
this.name = name
this.age = age
console.log(this)
}
let con = new Con('con', 3)
5. 事件处理函数中的this,this指向当前节点。
let oBtn = document.getElementById('btn');
oBtn.addEventListener('click', function () {
console.log(this);
});
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>