this指向:默认绑定,隐士绑定,显示绑定,new绑定。
this指向window几种情况:
1:指向window
function fn(){
console.log(this) //window
}
2:
setTimeOut(function () {
console.log(this)//window
},0)
function Person(){
this.name = 'Smiley';
this.sayName=function(){
console.log(this);
console.log(this.name);
};
setTimeout(this, 0); // window
}
var person = new Person();
person.sayName(); // person
3:
回调函数中的this指向window
4:
var x = {
• p:0,
• b:{
• p:2,
• fn:function(){
• console.log(this)
• Console.log(this.p)
• }
• }
• }
• let m = x.b.fn; 只是将x对象下的方法赋值给m,并没有调用
• m() 调用此时绑定的对象是window,并非b对象直接调用
5:
var ob ={
x:0,
z:0,
fn:function (x,z){
//内部函数
var fnn =function (x){
this.x=x
}
//内部函数
var fm =function (z){
this.z=z
}
fnn(x); //全局调用
fm(z) //全局调用
}
}
ob.fn(2,3)
log(ob.x) //0
log(ob.y) //0
6:
var k = {
a:0,
b:{
fn:function(){
console.log(this); //{fn:f}
console.log(this.a); //undefined
}
}
}
k.b.fn()
7
var point = {
x : 0,
y : 0,
moveTo : {
// 内部函数
moveX: function(x) {
console.log(this) // {moveX: ƒ, moveY: ƒ} moveTo没有变量x,y
this.x = x;
},
// 内部函数
moveY: function(y) {
this.y = y;
}
}
};
point.moveTo.moveX(1);
point.moveTo.moveY(1);
console.log(point.moveTo); // {moveX: ƒ, moveY: ƒ, x: 1, y: 1}
console.log(point.x); // 0
console.log(point.y); // 0
console.log(x) // x is not defined
console.log(y) //
回调函数的this指向window
var a = 10;
var foo = {
a: 20,
fn: (function(){
console.log(this); // window
console.log(this.a); // 10
})()
}