<script>
//class function for defining instances of a closure demo
function ClosureDemo2() {
var _a = 0, _b = 0; //private properties prefixed with an underscore to denote that they
//cannot be accessed outside of the instance
this.c = 0; //public property
//private function declared as a variable
var _doSomething = function() {
alert('doing something...');
};
//private function declared as a function shorthand for var _doAnotherSomething = function() {}
function _doAnotherSomething() {
alert('doing another something...');
}
//privileged and public function privileged, because it can access the private vars
this.Increment = function() {
_a++; //this works here
_b++; //this works here
this.c++; //this, of course, works here
};
//privileged and public function privileged, because it can access the private vars
this.Print = function() {
_doAnotherSomething(); //this works here
alert("a = " + _a.toString() + "\n" +"b = " + _b.toString() + "\n" +"c = " + this.c.toString() + "\n");
};
alert('initializing an instance of this class...');
_doSomething(); //this works here
//*NOTE: The following will not work //这个与Java不同
//this._a, this._b, this._doSomething(), this._doAnotherSomething()
}
var myDemo1 = new ClosureDemo2();
ClosureDemo2.prototype.IncrementAgain = function() { //public method can access to public var,
//但是不能访问private var, 这个与Java不同
//_a++; //this fails here
//_b++; //this fails here
this.c++; //this works here
};
var myDemo2 = new ClosureDemo2();
myDemo1.Increment(); //this will work here
myDemo2.Increment(); //this will work here
//these 2 lines will fail here
//myDemo1._a = 2;
//myDemo1._b = 2;
myDemo1.c = 2; //this will work here
myDemo2.c = 2; //this will work here
//these 2 lines will also fail here
//myDemo1._doSomething();
//myDemo1._doAnotherSomething();
//because the prototype of the class was changed after myClass1 was created, this fails。
//myDemo1.IncrementAgain(); //这个就太奇怪了,public method要使用前添加
//but, this works
myDemo2.IncrementAgain();
myDemo1.Print(); //this will work here
myDemo2.Print(); //this will work here
</script>
In the code below there is a scoping error:
function ClosureDemo()
{
var a = b = 0; /*
The first error is in the declaration of the a and b variable. In the above code, I only declared the variable a in the scope of the function. Variable b is not declared, and was merely initialized to 0. Instead, since variable b is not being declared, the variable will be created (if necessary) in the global scope and initialized to 0. Now, b, instead of being a variable local to each instance of the closure, acts as a global variable. */
this.Test = function()
{
a++;
b++;
}
}