zoukankan      html  css  js  c++  java
  • JavaScript对象中的this属性

    this属性表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window;

    如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用。

    我们还可以使用apply和call两个全局方法来改变函数中this的具体指向。

    先看一个在全局作用范围内使用this的例子:

    1. 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.  1 // 定义一个全局函数  
       2 function foo() {  
       3     console.log(this.fruit);  
       4 } 
       5  
       6 // 定义一个全局变量,等价于window.fruit = "apple";  
       7 var fruit = "apple"; 
       8  
       9 // 此时函数foo中this指向window对象  
      10 // 这种调用方式和window.foo();是完全等价的  
      11 foo();              // "apple"  
      12  
      13 // 自定义一个对象,并将此对象的属性foo指向全局函数foo  
      14 var pack = {  
      15     fruit: "orange",  
      16     foo: foo  
      17 };  
      18 
      19 // 此时函数foo中this指向pack对象  
      20 pack.foo();     // "orange"              

    全局函数apply和call可以用来改变函数中this属性的指向,如下:

    1.  1 // 定义一个全局函数  
       2  function foo() {  
       3      console.log(this.fruit);  
       4  }  
       5    
       6  // 定义一个全局变量  
       7  var fruit = "apple"; 
       8  
       9  // 自定义一个对象  
      10  var pack = {  
      11      fruit: "orange" 
      12  };  
      13    
      14  // 等价于window.foo();  
      15  foo.apply(window);  // "apple" 
      16  
      17  // 此时foo中的this === pack  
      18  foo.apply(pack);    // "orange"   

    注:apply和call两个函数的作用相同,唯一的区别是两个函数的参数定义不同。

    因为在JavaScript中函数也是对象,所以我们可以看到如下有趣的例子:

    1.  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 
      17 // 等价于window.foo();  
      18 foo();      // this is window.  
      19  
      20 // 可以看到函数中this的指向调用函数的对象  
      21 foo.boo();      // this is foo.  
      22  
      23 // 使用apply改变函数中this的指向  
      24 foo.boo.apply(window);      // this is window.(使用apply)  
  • 相关阅读:
    正则表达式
    HashTable与HashMap的区别
    求解连续子数组乘积的最大值
    求解N个值中最大的k个数,N远大于k
    C++权限修饰符
    DBSCAN算法
    【leetcode】1318. Minimum Flips to Make a OR b Equal to c
     【leetcode】1317. Convert Integer to the Sum of Two No-Zero Integers
    【leetcode】1316. Distinct Echo Substrings
    【leetcode】1315. Sum of Nodes with Even-Valued Grandparent
  • 原文地址:https://www.cnblogs.com/ttcc/p/3748801.html
Copyright © 2011-2022 走看看