문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top