Skip to content Skip to sidebar Skip to footer

Inheritance With Lo-dash

I am trying to emulate inheritance in javascript using a the Lo-Dash javascript library. I am simply using _.extend to do so: function Parent() { var self = this; self.hello =

Solution 1:

See _.create documentation for a working example.

Solution 2:

Parent is simply the constructor for the Parent class, it does not itself have the hello property that it adds to self. You could just change the _.extend line to this: _.extend(self, new Parent()) to solve it. This works because the object returned by new Parent() does have a hello property that _.extend can copy over to self.

To access the hello property you will also have to create an instance of the Child class rather than accessing hello on the constructor. After making the above change, (new Child()).hello() should work because you accessing the hello property on the Childinstance not the constructor.

But, this seems to me to be a poor solution because new Child() instanceof Parent will return false. If you want to properly set up the prototype chain so there is "true" inheritance going on you should read about psuedoclassical and prototypal inheritance.

Solution 3:

You could use _.create() function and prototype to emulate inheritance.

functionParent() {}

Parent.prototype.hello = function() {
    console.log('Hello from parent');
};

functionChild() {}

Child.prototype = _.create(Parent.prototype, {
    'constructor': Child
});

var child = newChild();
child.hello(); //Hello from parent

Post a Comment for "Inheritance With Lo-dash"