写了一个小demo,关于this指向问题的探讨
var name = 10;
// test();
function test(){
this.name = 5;
console.log(this);
console.log(this.name)
setTimeout(function nice(){
console.log(this);
console.log(this.name);
},1000);
};
var p = new test();
输出结果为
test{
name:5}
5
window{
...}
10
原因是new test{ }创建了一个test对象,对象内的this.name 赋值为5
而setTimeout中执行的函数:
{
超时调用的代码都是在全局作用域中执行的,因此函数中this的值在非严格模式下指向window对象,在严格模式下是undefined
}
指向window因而在setTimeout中的函数输出的this.name 值为10
如果使用test():直接调用test函数呢?
var name = 10;
// test();
function test(){
this.name = 5;
console.log(this);
console.log(this.name)
setTimeout(function nice(){
console.log(this);
console.log(this.name);
console.log("*********");
},1000);
};
test();
输出结果:
window{
...}
5
window{
...}
5
原因是,在全局中执行了函数,因而this.name = 5;覆盖了全局变量中的name值
如果想要setTimeout里面还保存test{ }对象内的值需要使用一个变量来保存this
function test(){
this.name = 5;
let that = this;
console.log(this);
console.log(this.name)
setTimeout(function nice(){
console.log(that);
console.log(that.name);
console.log("*********");
},1000);
};
这样that一直指向test对象了
function a(){
var name = "billmian";
console.log(this.name); //undefined
console.log(this); //Window
}
a();
this最终指向的是调用它的对象
因为,调用a()函数的相当于是window
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();