JavaScript类和继承:this属性

来源:互联网 发布:吞食天地软件 编辑:程序博客网 时间:2024/05/06 18:48

转自 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.