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.
JavaScript objects have two types of properties: data properties and accessor properties.
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.
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.
There is only one BaseObject
instance from which all TestObject
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With