一、this指向的定律
- 函数声明的时候决定不了this指向,在调用的时候决定,谁调用了这个函数就指向谁;
- this永远指向最近一个调用他的对象;
- 构造函数会自动把this指向实例对象;
- 如果构造函数内部有return出对象,那么this指向这个return出的对象;
二、代码片段
// 1 window调用了a()
function a(){
var user = "赵敏";
console.log(this.user); //undefined
console.log(this); //Window
}
a();
// 2 o 调用了fn()
var o = {
user:"赵敏",
fn:function(){
console.log(this.user); //赵敏
}
}
o.fn();
// 3 // fn()最近的b调用了fn()
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();
// 4 最终是window调用了j() ,j 调用了o.b.fn
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
// 5 this指向了a
function Fn(){
this.user = "赵敏";
}
var a = new Fn();
console.log(a.user); //赵敏
// 6 this指向return出的对象
function fn()
{
this.user = '赵敏';
return {};
}
var a = new fn;
console.log(a.user); //undefined