The below code is taken from http://bonsaiden.github.com/JavaScript-Garden/
function Foo() {
this.value = 42;
}
Foo.prototype = {
method: function() {}
};
function Bar() {}
// Set Bar's prototype to a new instance of Foo
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';
// Make sure to list Bar as the actual constructor
Bar.prototype.constructor = Bar;
I have come across this explanation multiple times "When accessing the property of an object, first it checks if the object its self has that property and if not than it goes to the prototype of that object to look for the property and so on."
But I am struggling to understand ho this actually works because of the behavior of the following code
var test1 = new Bar();
var test2 = new Bar();
test1.value = 24;
now value is not part of the test1 object but it is a property of its prototype which is a Foo Object, and since the prototype is a Foo Object all instances of Bar will share the value property, What i expect the above code to do is to set that value property to 24 but instead it creates a new property named 'value' to the test1 object and assigns it 24 leaving the value property in the prototype to its initial value 42. well this doesn't sound like sharing. test2.value still has a value of 42. when i look at the prototype chain in the firebug console it shows me that test1 has a value property with 24 and its prototype has a value property with 42.
This is very confusing to. Has any one you figured out why it behaves this way ?