你不知道的JavaScript(this)

來源:互聯網
上載者:User

標籤:全域對象   name   bsp   java   函數調用   隱式   his   foo   ide   

 

對this的常見誤解

  this指向函數本身;

  this指向函數的詞法範圍;

this是在運行時進行綁定的,並不是在編寫時,它的上下文取決於函數調用時的條件。

this的綁定和函式宣告的位置沒有任何關係,只取決於函數的調用方式。

function identify() {  return this.name.toUpperCase();}function speak() {  var greeting = “Hello, I’m” + identify.call(this);  console.log(greetin);}var me = {  name: “Kyle"};var you = {  name: “Reader"};identify.call(me);identify.call(you);speak.call(me);speak.call(you);

 

對象屬性引用鏈中只有最頂層或者說最後一層會影響調用位置

function foo() {  console.log(this.a);}var obj2 = {  a: 42,  foo: foo};var obj1 = {  a: 2,  obj2: obj2};obj1.obj2.foo(); // 42

 

判斷this的順序:

  ?函數是否在new中調用(new綁定)?如果是的話this綁定的是新建立的對象

    var bar = new foo()

  ?函數是否通過call、apply(顯示綁定)或者硬綁定調用?如果是的話,this綁定的是指定的對象

    var bar = foo.call(obj2)

  ?函數是否在某個內容物件中調用(隱式綁定)?如果是的話,this綁定的是那個內容物件

    var bar = obj1.foo();

  ?如果都不是的話,使用預設綁定。strict 模式下,綁定到undefined,否則綁定到全域對象。

 

你不知道的JavaScript(this)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.