Javascript:必須知道的Javascript知識點之“this指標”

來源:互聯網
上載者:User
文章目錄
  • 規則1
  • 規則2
  • 規則3
  • 使用apply
  • 使用call
很多人都知道this指標,這篇文章的主要目的是為了培訓我們公司的新人。預設的this指標指向規則1

this指標預設指向方法調用時為其指定的對象,如:obj.fun(),fun方法體中的this指標指向obj。

1 var user = { name: '段光偉' };2 user.getName = function(){ return this.name; };3 user.getName();  //返回‘段光偉’
1 var user = { name: '段光偉' };2 user.getName = function(){ return this.name; };3 user.getName();  //返回‘段光偉’4 5 window.name = '李妞妞';6 window.getName = user.getName7 window.getName();  //返回‘李妞妞’8 getName();  //返回‘李妞妞’
規則2

如果在方法調用時沒有為方法指定對象則this指標預設指向window,如:fun(),fun方法體中的this指標指向window。

1 var fun = function(){2   return this;3 }4 fun();  //返回window對象
規則3

沒有在方法體中的代碼可以看作執行在一個匿名方法,根據規則2可以推論出其this指標指向window。

1 this  //window對象
改變this指標的預設指向使用apply
1 var user = { name: '段光偉' };2 user.hi= function(message){ return this.name+':'+message; };3 window.name = '李妞妞'4 user.hi('你好');  //輸出‘段光偉:你好’5 user.hi.apply(window, ['你好']);  //輸出‘李妞妞:你好’
使用call
1 var user = { name: '段光偉' };2 user.hi= function(message){ return this.name+':'+message; };3 window.name = '李妞妞'4 user.hi('你好');  //輸出‘段光偉:你好’5 user.hi.call(window, '你好');  //輸出‘李妞妞:你好’
建構函式中的this指向建構函式中的this指標預設指向執行正在構造的對象。
1 var User = function(name){2    this.name = name;3 };4 User.prototype.hi = function(){5    return this.name;6 };7 var user = new User('段光偉');8 user.hi();  //輸出‘段光偉’
最後的小測試猜猜最後的輸出時什嗎?
 1 var User = function(name){ 2     this.name = name; 3  }; 4  User.prototype.hi = function(){ 5     return this.name; 6  }; 7  var user = new User('段光偉'); 8  user.hi();  //輸出‘段光偉’ 9 10 var hi = user.hi;11 12 hi();  //猜猜這裡的輸出
object expression.method();會被翻譯為object expression.method.call(object expression);。而var temp = object expression.method;temp();會被翻譯為var temp = object expression.method;temp.call(window)。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.