Java类中的this

this是个很神奇的东西,我们先看看JavaScript中的this

var namespace = function(){};
        
namespace.prototype.tableList = [];
        
namespace.prototype.setName = function(_name){
    this.Name = _name;
}
        
namespace.prototype.setVersion = function(_version){
    this.Version = _version;
}
        
namespace.prototype.methodTable = function(_methodName){            
    this.tableList.push(_methodName);
}
        
var java = new namespace();
java.setName("Java");
java.setVersion("1.0.0.1");
java.methodTable("func");

呵呵,神奇的this,还有好多,JavaScript中的this更灵活,在function中,在object中,当然了闭包中的this等等。。。

在回来看看java中this

java中的this指向调用方法的当前对象。实际上this就是当前的实例对象。实例对象有什么样的域,有什么样的方法,都可以this调用。

例如我们在说封装类的域的时候我访问域都没有用this,java里面不用特别的指定,编译器会自动完成,有一种情况必须加this,看代码

class TPerson{
    private double salary;
    
    public void setSalary(double salary) {
        this.salary = salary;
    }
}

当参数名和域名完全相同的时候必须加this表明是指的哪一个。

posted on 2012-10-05 23:19  kiny  阅读(367)  评论(0编辑  收藏  举报