this的理解

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
    })()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值