Reputation: 507
Here is what I did.
var A = function() {
var internal = 0;
this.increment = function() {
return ++internal;
};
};
var B = function() {};
// inherit from A
B.prototype = new A;
//first case
x = new B;
y = new B;
//second case
z = new A;
z1 = new A;
alert(x.increment() + " - " + y.increment());
alert(z.increment() + " - " + z1.increment());
The private variables are behaving like static variables in first case, where as they are behaving like normal variables in second case.
1) Is there something we can conclude from above behaviour about private variables OR anything else?
2) One supplementary question that just popped up - When we add properties and methods to a constructor function using prototypes, there is only one method, and this is shared among all the instances(objects) created, same thing applied to variables?
Upvotes: 1
Views: 72
Reputation: 2863
To answer your second supplementary question, consider the following:
var A = function(){};
A.prototype.num = 0;
A.prototype.num2 = 0;
A.prototype.increment = function(modifyNum){
console.log("increment");
++A.prototype.num;
if(modifyNum == true){
console.log("modifying num");
this.num = 0;
}
console.log("num", this.num);
++this.num2;
console.log("num2", this.num2);
}
var test1 = new A();
test1.increment();
var test2 = new A();
test2.increment();
var test3 = new A();
test3.increment(true);
var test4 = new A();
test4.increment();
The output will be:
increment
num 1
num2 1
increment
num 2
num2 1
increment
modifying num
num 0
num2 1
increment
num 4
num2 1
You can see the class instance will respect the prototype up until the class itself modifies num directly, and therefore it redefines it within its own scope. In the third test, num is modified directly and its value no longer points to the prototype. All of this is inherently leaky for a beginner when doing more than incrementing a number when used in practice such as tracking class instances. Be careful out there.
Upvotes: 1
Reputation: 7698
It is just concept of scope of that variable.
First case.
In first case, you are inheriting class A, i.e. Creating another class with the prototype returned by instance of class A.
And thats why variable increment will work as static way because it gets declared only once.
Second Case
In second case, you are creating instance of class A twice. so variable instance will gets declared twice and have separate memory location for both instances.
Just remember,
The body of function gets executed when you call that function or you create instance of that function.
Upvotes: 0