Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my JavaScript object properties being overwritten by other instances?

I created an object like the following.

var BaseObject = function(){

var base = this;
base.prop;

base.setProp = function(val){
    base.prop = val;
}
}

When I call the setProp method, I get the following.

var a = new BaseObject();
var b = new BaseObject();           

a.setProp("foo");
b.setProp("bar");

console.log(a.prop); // outputs 'foo'
console.log(b.prop); // outputs 'bar'

I then created another object that inherits from BaseObject like this.

var TestObject = function(){
    // do something
}

TestObject.prototype = new BaseObject();

When I do the same, I get a result I wasn't expecting.

var a = new TestObject();
var b = new TestObject();

a.setProp("foo");
b.setProp("bar");

console.log(a.prop); // outputs 'bar'
console.log(b.prop); // outputs 'bar'

I don't know why. I've been reading alot about closures and prototypal inheritance recently and I suspect I've gotten it all confused. So any pointers on why this particular example works the way it does would be greatly appreciated.

like image 740
gargantuan Avatar asked Oct 29 '12 18:10

gargantuan


People also ask

What are the two kinds of objects properties we can have in JavaScript?

JavaScript objects have two types of properties: data properties and accessor properties.

What is object instances in JavaScript?

Object is the instance of the class that have some memory and instance is a variable & methods that object have. Reference means address of object or variable. Object is instance of class and instance means representative of class i.e object. Instance is the actual object created at run time.

Does object assign return new object?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


1 Answers

There is only one BaseObject instance from which all TestObjects inherit. Don't use instances for creating prototype chains!

What you want is:

var TestObject = function(){
    BaseObject.call(this); // give this instance own properties from BaseObject
    // do something
}
TestObject.prototype = Object.create(BaseObject.prototype);

See JavaScript inheritance: Object.create vs new, Correct javascript inheritance and What is the reason to use the 'new' keyword at Derived.prototype = new Base for a detailed explanation of the problems with new. Also have a look at Crockford's Prototypal inheritance - Issues with nested objects

like image 120
Bergi Avatar answered Oct 11 '22 18:10

Bergi