this出现在全局函数中,永远指向window
var Car = function() {
console.log(this); // window
console.log(this.Car==window.Car,Car==window.Car); // true true
}
Car();
函数中使用es5的严格模式‘use strict’,this为undefined
var Car = function() {
'use strict'
console.log(this); // undefined
}
Car();
当某个函数为对象的一个属性时,在这个函数内部this指向这个对象
var car = {
name:'张三',
run() {
console.log(this); // {name: "张三", run: ƒ}
}
}
构造函数中的this,指向构造函数新创建的对象
var Car = function(name) {
this.name = name;
console.log(this); // Car {name: "张三"}
// Car {name: "李四"}
}
var myCar_1 = new Car('张三');
var myCar_2 = new Car('李四');
绑定事件中的this,指向被点击的这个元素
var btn = document.querySelector('button');
btn.onclick = function() {
console.log(this); // <button>this</button>
}
箭头函数没有this,它的this是继承而来,默认指向在定义它时所处的对象
const obj = {
Car() {
setTimeout(function() {
setTimeout(function() {
console.log(this); // window
})
setTimeout(()=>{
console.log(this); // window
})
})
setTimeout(() => {
setTimeout(function() {
console.log(this); // window
})
setTimeout(()=>{
console.log(this); // obj
})
})
}
}
obj.Car()