Question

Use the following simple example:

var MyObject = {
    name: '',
    object_id: '',
    awesomeFunction: function() { console.log('awesome'); }
};

Now, this is fine until I think about prototypal inheritance. Say i now want to inherit from this object:

 var child_object = Object.create(MyObject);

This instantly causes problems because the child object has not specified the name and object_id properties which will therefore be taken from the parent object (prototype). And there is no native way to enforce that child objects are created with their own versions of these, right?

Is this understanding correct?

If so, am i thinking about inheritance in javascript incorrectly?

Should objects be treated as containers for functions instead?

Was it helpful?

Solution

And there is no native way to enforce that child objects are created with their own versions of these, right?

If you want all the instances to have those attributes, by default, then you should not inherit but construct them. The normal way to do this would be

function Parent(name, id) {
    this.name = name;
    this.id   = id;
}

function Child(name, id) {
     Parent.call(this, name, id);
}

Now, when you create an instance of Child, they will have their own version of name and id. Also, you can assign values to them while creating them itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top