Judging by the # of “javascript inheritance” questions here I am going to assume my question was probably already answered elsewhere and I am just not understanding the other solutions…or javascript in general apparently.
My question is, why does the code below ( http://jsfiddle.net/Se9ZW/2/ ) print “test5” instead of “test1”?
var fake = { value:'test1'};
var fake2=fake;
fake2.value='test5';
document.getElementById('debug').innerHTML=fake.value;
These seems like something that is pretty obvious and so I am kinda embarassed to even be bringing it up but I guess ya gotta learn somehow.
fakeandfake2are references to the same object, so it is totally expected that they behave that way. It has nothing to do with inheritance.Now, if you wanted to inherit, one way (quite naive, I might add) would be to do it like this:
and the output then would be:
Note that this is from ECMAScript Edition 5 – which is fairly recent and may not work in every JavaScript engine implementation out there.
There are several way to implement/use inheritance in JavaScript. I am going to refer you to one of the explanations in accepted answer here.