Inheritance with Lo-Dash

I am trying to emulate inheritance in javascript using the Lo-Dash JavaScript library.

I just use _.extend to do this:

function Parent() {
  var self = this;

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

function Child() {
  var self = this;

  _.extend(self, Parent);
}

Child.hello(); // Doesn't exist

      

I thought this would work since all javascript functions are objects, but obviously I am wrong. Why doesn't this work and how do I correctly emulate inheritance with Lo-Dash?

+3


source to share


3 answers


The parent is just the constructor of the Parent class, it does not itself have the property hello

that it adds to self

. You can just change the line _.extend

to this: _.extend(self, new Parent())

to fix this problem. This works because the object returned new Parent()

has a property hello

that _.extend

can be copied to self

.

To access the property hello

, you also need to instantiate the class Child

instead of accessing it hello

in the constructor. After doing the above change (new Child()).hello()

should work because you are accessing a property hello

on an instance Child

not a constructor.



But this seems like a bad decision to me because it new Child() instanceof Parent

will return false

. If you want to properly set up the prototype chain for "true" inheritance to occur, you should read about pseudo-classical and prototypal inheritance.

+6


source


See the _.create documentation for a working example.



+13


source


You can use _.create()

it prototype

to emulate inheritance as well.

function Parent() {}

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

function Child() {}

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

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

      

+2


source







All Articles