原则谁调用,就指向谁
1.普通函数
function add(){
console.log(this)
}
add()
this指向window
2.对象.函数()
var x = 100;
const obj = {
x: 19,
y: 20,
add: function () {
return this.x + this.y;
}
}
const sum=obj.add();
console.log(sum);//39
this指向方法所属对象
3.构造函数中的this
function Star(name,age){
this.name=name;
this.age=age;
}
Star.prototype.sing=function(){
console.log(this)
}
let star=new Star('tom',18)
star.sing();
this指向实例对象
4.定时器
setTimeout(
function(){
console.log(this)
},1000
)
this指向window
5.闭包中的this对象
<1 >this指向window对象
var name = "window对象";
var obj = {
name: "Object对象",
getName: function () {
return function () {
return this.name;
}
}
}
console.log("name=", obj.getName()());
name=window对象
<2>this指向外部函数的执行环境
var name = "window对象";
var obj = {
name: "Object对象",
getName: function () {
var that = this;
return function () {
return that.name;
}
}
}
console.log("name=", obj.getName()());
name= Object对象