malonso
malonso

Reputation: 2295

Javascript inheritance issue

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.

Upvotes: 1

Views: 105

Answers (4)

Upgradingdave
Upgradingdave

Reputation: 13056

Maybe you're getting confused by terminology? Here's an explanation without the words "reference" and "value":

{ value:'test1'} is a Object. You can think of it like a bucket full of things. In this case, the bucket has one thing inside named value.

On line 1, you're pointing fake to the bucket. On line 2, you're pointing fake2 to fake. Since fake is just pointing to a bucket, fake2 also points to the exact same bucket.

On line 3, fake2.value is the thing named value in the bucket. fake2.value is the same thing in the same bucket.

Another way to say this same thing is that primitives (think: concrete things) are passed by value, and objects (think: containers and/or buckets) are passed by reference in javascript.

Upvotes: 1

ZenMaster
ZenMaster

Reputation: 12742

fake and fake2 are 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:

var fake = { value:'test1'};
var fake2 = Object.create(fake); //creates a new object with fake as prototype
fake2.value = 'test5'; // "overrides" the value property from the prototype
console.log(fake.value);

and the output then would be:

test1

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.

Upvotes: 4

red-X
red-X

Reputation: 5128

Because javascript passes by reference, meaning fake2 is not a copy of fake, it is another name of fake and in fact the same object.

Upvotes: 0

Dogbert
Dogbert

Reputation: 222158

This is because

var fake2 = fake;

creates a reference of fake into fake2. If you change anything in fake2, fake also gets changed.

Upvotes: 1

Related Questions