zoukankan      html  css  js  c++  java
  • this

    JS中this关键字

    在学习js时,应该先了解下this关键字,关于js中的this关键字和其他的面向对象语言中的this是不同的,比如在java中,this指的的是当前对象,而在js中,w3c是这样规定的:

    关键字 this

    this 的功能

    在 ECMAScript 中,要掌握的最重要的概念之一是关键字 this 的用法,它用在对象的方法中。关键字 this 总是指向调用该方法的对象,例如:

    var oCar = new Object;
    oCar.color = "red";
    oCar.showColor = function() {
      alert(this.color);
    };
    
    oCar.showColor();		//输出 "red"
    

    在上面的代码中,关键字 this 用在对象的 showColor() 方法中。在此环境中,this 等于 oCar。下面的代码与上面的代码的功能相同:

    var oCar = new Object;
    oCar.color = "red";
    oCar.showColor = function() {
      alert(oCar.color);
    };
    
    oCar.showColor();		//输出 "red"
    

    使用 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"
    

    在上面的代码中,首先用 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"。


    在w3c中定义很明确,this是指向调用该方法的对象。在实际操作中有很多情况让我们摸不清头脑,下面举几个例子,让我们更好的理解this。

    在学习js闭包的时候看到这样一篇文章,里面有个思考题。

    var name = "The Window";   
      var object = {   
        name : "My Object",   
        getNameFunc : function(){   
          return function(){   
            return this.name;   
         };   
        }   
    };   
    alert(object.getNameFunc()());  
    //The Window

  • 相关阅读:
    js反爬:请开启JavaScript并刷新该页
    VIEWSTATE等参数处理
    VM+CentOS+Hadoop+Spark集群搭建
    从入门到自闭之Python入门
    从入门到自闭之Python软件命名规范
    从入门到自闭之Python序列化
    从入门到自闭之Python名称空间
    从入门到自闭之Python函数初识
    从入门到自闭之Python随机模块
    从入门到自闭之Python时间模块
  • 原文地址:https://www.cnblogs.com/xiaoleidiv/p/3335390.html
Copyright © 2011-2022 走看看