Inheritance with Lo-Dash

[亡魂溺海] 提交于 2021-02-10 03:28:10

问题


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 = 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 would I properly emulate inheritance using Lo-Dash?


回答1:


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 Child instance 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.




回答2:


See _.create documentation for a working example.




回答3:


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

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


来源:https://stackoverflow.com/questions/25149713/inheritance-with-lo-dash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!