JavaScript如何擷取對象執行個體的名字

來源:互聯網
上載者:User

標籤:

  大家都知道JavaScript是一種物件導向的語言,對象可以通過new關鍵字,執行個體化出來,但是,如果我想擷取執行個體化對象的名字,怎麼破?比如:

1 function Dog() {2     this.myName = function() {3     }4 };5 6 var dog = new Dog();

  如何擷取這個dog的名字"dog"呢?大家想過沒,可以先想想!

  其實大家想過沒有,定義的全域變數為什麼能夠直接存取使用呢?實際上全域變數是綁定在window對象上的,都是window對象的屬性,如下:

1 var age = 20;2 console.log(window.age);  // 輸出 20

  好了,我們返回上面的例子,那麼dog其實也是綁定在window對象上的,如下:

1 function Dog() {2     this.myName = function() {3     }4 };5 var dog = new Dog()6 console.log(window.dog); // 輸出 Dog {}

  那麼接下來,就可以利用這個特點,來搞點什麼,如下:

 1 function Dog() { 2     this.myName = function() { 3                  4         // 這裡迴圈尋找window對象中的dog屬性 5         for (var name in this.global) { 6                        7             // 判斷是否為Dog類 8             if (this.global[name] === this) { 9                 return name;10             }11         }12     }13 }14 15 // 這裡,將window對象的引用,存到Dog原型的global中16 Dog.prototype.global = this;17 18 var dog = new Dog();19 20 console.log(dog.myName());  // 輸出"dog"            

  就這樣,就擷取了執行個體化對象的名字了,nice!

  總結:

  1. 該方法的主要原理是通過全域變數的儲存機制,是綁定在window對象上的;
  2. 什麼時候需要去擷取執行個體化對象的名字呢?一般的情境都不需要吧,這個主要是dog是個對象,但是我時候要把它當做字串來用,比如列印日誌,構造了"dog"對象,這個時候,其實就派上用場了。
  3. dog是自己執行個體化的,肯定是隨機的,這時,只能通過一個中間媒介來儲存,並實現轉化。

JavaScript如何擷取對象執行個體的名字

聯繫我們

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