zoukankan      html  css  js  c++  java
  • 关于this

    this 的功能
    在 ECMAScript 中,要掌握的最重要的概念之一是关键字 this 的用法,它用在对象的方法中。关键字 this 总是指向调用该方法的对象,例如:
    
    var oCar = new Object;
    oCar.color = "red";
    oCar.showColor = function() {
      alert(this.color);
    };
    
    oCar.showColor();		//输出 "red"
    TIY
    
    在上面的代码中,关键字 this 用在对象的 showColor() 方法中。在此环境中,this 等于 oCar。下面的代码与上面的代码的功能相同:
    
    var oCar = new Object;
    oCar.color = "red";
    oCar.showColor = function() {
      alert(oCar.color);
    };
    
    oCar.showColor();		//输出 "red"
    TIY
    
    使用 this 的原因
    为什么使用 this 呢?因为在实例化对象时,总是不能确定开发者会使用什么样的变量名。使用 this,即可在任何多个地方重用同一个函数。请思考下面的例子:
    
    function showColor() {
      alert(this.color);
    };
    
    var oCar1 = new Object;
    oCar1.color = "red";
    oCar1.showColor = showColor;
    
    var oCar2 = new Object;
    oCar2.color = "blue";
    oCar2.showColor = showColor;
    
    oCar1.showColor();		//输出 "red"
    oCar2.showColor();		//输出 "blue"
    TIY
    
    在上面的代码中,首先用 this 定义函数 showColor(),然后创建两个对象(oCar1 和 oCar2),一个对象的 color 属性被设置为 "red",另一个对象的 color 属性被设置为 "blue"。两个对象都被赋予了属性 showColor,指向原始的 showColor () 函数(注意这里不存在命名问题,因为一个是全局函数,而另一个是对象的属性)。调用每个对象的 showColor(),oCar1 输出是 "red",而 oCar2 的输出是 "blue"。这是因为调用 oCar1.showColor() 时,函数中的 this 关键字等于 oCar1。调用 oCar2.showColor() 时,函数中的 this 关键字等于 oCar2。
    
    注意,引用对象的属性时,必须使用 this 关键字。例如,如果采用下面的代码,showColor() 方法不能运行:
    
    function showColor() {
      alert(color);
    };
    如果不用对象或 this 关键字引用变量,ECMAScript 就会把它看作局部变量或全局变量。然后该函数将查找名为 color 的局部或全局变量,但是不会找到。结果如何呢?该函数将在警告中显示 "null"。
    

      

  • 相关阅读:
    ZJOI2019二轮游记
    Luogu P5284 [十二省联考2019]字符串问题
    Luogu P5309 [Ynoi2012]D1T1
    Luogu P5292 [HNOI2019]校园旅行
    LOJ #6052. 「雅礼集训 2017 Day11」DIV
    Luogu P5279 [ZJOI2019]麻将
    LOJ #6060. 「2017 山东一轮集训 Day1 / SDWC2018 Day1」Set
    Luogu P5283 [十二省联考2019]异或粽子
    Luogu P5290 [十二省联考2019]春节十二响
    Luogu P5285 [十二省联考2019]骗分过样例
  • 原文地址:https://www.cnblogs.com/mingjixiaohui/p/5511813.html
Copyright © 2011-2022 走看看