1. 全局作用域或者普通函数中 this 指向全局对象 window。
console.log(this)
function bar () {console.log(this)}
bar()
var bar = function () {console.log(this)}
bar()
(function () {console.log(this)})();
2. 方法调用中谁调用 this 指向谁。
var person = {
run: function () {console.log(this)}
}
person.run()
var btn = document.querySelector("button")
btn.onclick = function () {
console.log(this)
}
var btn = document.querySelector("button")
btn.addEventListener('click', function () {
console.log(this)
})
$.ajax({
self: this,
type: "get",
url: url,
async: true,
success: function (res) {
console.log(this)
console.log(self)
}
});
3. 在构造函数或者构造函数原型对象中 this 指向构造函数的实例。
function Person(name) {
console.log(this)
this.name = name;
}
Person('inwe')
function Person(name) {
this.name = name
console.log(this)
self = this
}
var people = new Person('iwen')
console.log(self === people)
4. 箭头函数中指向外层作用域的 this。
var obj = {
foo() {
console.log(this);
},
bar: () => {
console.log(this);
}
}
obj.foo()
obj.bar()
转载自