JavaScript類和繼承:this屬性

轉自 http://developer.51cto.com/art/200902/111044.htm

  • 本文介紹了JavaScript裏面的this屬性。這個屬性是理解JavaScript類和繼承的重要基礎。

this屬性表示當前對象,如果在全局作用範圍內使用this,則指代當前頁面對象window; 如果在函數中使用this,則this指代什麼是根據運行時此函數在什麼對象上被調用。 我們還可以使用apply和call兩個全局方法來改變函數中this的具體指向。
先看一個在全局作用範圍內使用this的例子:

  1. <
     
    script
     
    type
    =
    "text/javascript"
    >
     



  2.     console.log(
    this
     === window);  // true  


  3.     console.log(
    window.alert
     === this.alert);  // true  


  4.     console.log(this.parseInt("021", 10));  // 10  


  5. <
     /script
    >
     



函數中的this屬性是在運行時決定的,而不是函數定義時,如下:

  1. // 定義一個全局函數

     



  2. function foo() {  


  3.     console.log(
    this


    .fruit);  


  4. }  


  5. // 定義一個全局變量,等價於window.fruit = "apple";

     


  6. var fruit = 
    "apple"

    ;  


  7. // 此時函數foo中this指向window對象

     


  8. // 這種調用方式和window.foo();是完全等價的

     


  9. foo();  
    // "apple"

     


  10.  


  11. // 自定義一個對象,並將此對象的屬性foo指向全局函數foo

     


  12. var pack = {  


  13.     fruit: 
    "orange"

    ,  


  14.     foo: foo  


  15. };  


  16. // 此時函數foo中this指向window.pack對象

     


  17. pack.foo(); 
    // "orange"

     


  18.  



全局函數apply和call可以用來改變函數中this屬性的指向,如下:

  1. // 定義一個全局函數

     



  2.  function foo() {  


  3.      console.log(
    this


    .fruit);  


  4.  }  


  5.    


  6.  
    // 定義一個全局變量

     


  7.  var fruit = 
    "apple"

    ;  


  8.  
    // 自定義一個對象

     


  9.  var pack = {  


  10.      fruit: 
    "orange"

     


  11.  };  


  12.    


  13.  
    // 等價於window.foo();

     


  14.  foo.apply(window);  
    // "apple"

     


  15.  
    // 此時foo中的this === pack

     


  16.  foo.apply(pack);    
    // "orange"

     


  17.   



注:apply和call兩個函數的作用相同,唯一的區別是兩個函數的參數定義不同。
因爲在JavaScript中函數也是對象,所以我們可以看到如下有趣的例子:

  1. // 定義一個全局函數

     



  2. function foo() {  


  3.     
    if


     (
    this


     === window) {  


  4.         console.log(
    "this is window."

    );  


  5.     }  


  6. }  


  7.  


  8. // 函數foo也是對象,所以可以定義foo的屬性boo爲一個函數

     


  9. foo.boo = function() {  


  10.     
    if


     (
    this


     === foo) {  


  11.         console.log(
    "this is foo."

    );  


  12.     } 
    else


     
    if


     (
    this


     === window) {  


  13.         console.log(
    "this is window."

    );  


  14.     }  


  15. };  


  16. // 等價於window.foo();

     


  17. foo();  
    // this is window.

     


  18.  


  19. // 可以看到函數中this的指向調用函數的對象

     


  20. foo.boo();  
    // this is foo.

     


  21.  


  22. // 使用apply改變函數中this的指向

     


  23. foo.boo.apply(window);  
    // this is window.




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章