码迷,mamicode.com
首页 > 其他好文 > 详细

this 的指向问题

时间:2019-10-17 17:55:11      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:调用   btn   settime   log   timeout   cti   console   问题   函数   

1.全局作用域或者普通函数中 this 指向全局对象 window ( 定时器里面的this 指向 window )

 1.1 console.log(this); // window

 1.2 function fn(){

   console.log( this );  // window

  }

 fn();   // 实际上是  window.fn(); 所以 this 也是 window

 1.3 window.setTimeout(function(){

    console.log(this); // window  

  },1000)

2.方法调用中谁调用 this 指向谁

 2.1 var o = {

   sayHi:function(){

     console.log(this);  //this 指向 o

   }

  }

 o.sayHi( );  // 因为是 o 调用了 sayHi 方法 所以 this 指向 o

 btn.onclcik = function (){

  console.log(this);  // btn

 }

3.构造函数中 this 指向构造函数的实例

 function Fun(){

  console.log(this);   // this 指向的是 fun 的实例对象

 }

 var fun = new Fun( ) ;   // new 创建了一个新的实例对象 赋值给 fun ,所以 this 指向 fun

 

this 的指向问题

标签:调用   btn   settime   log   timeout   cti   console   问题   函数   

原文地址:https://www.cnblogs.com/qtbb/p/11693119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!