Lo-Dash的继承 [英] Inheritance with Lo-Dash

查看:22
本文介绍了Lo-Dash的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Lo-Dash javascript库在javascript中模拟继承.

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

我只是使用 _.extend 来做到这一点:

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

我认为这将可行,因为所有javascript函数都是对象,但显然我错了.为什么这样做不起作用,如何使用Lo-Dash正确模拟继承?

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?

推荐答案

Parent只是Parent类的构造函数,它本身不具有添加到 self中的 hello 属性.您只需将 _.extend 行更改为此: _.extend(self,new Parent())即可解决.之所以可行,是因为通过 new Parent()返回的对象确实具有 hello 属性,该属性可以复制 _.extend 移到 self .

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.

要访问 hello 属性,您还必须创建 Child 类的 instance ,而不是访问 hello 在构造函数上.完成上述更改后,(new Child()).hello()应该可以工作,因为您访问了 Child hello 属性> instance 而不是构造函数.

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.

但是,在我看来,这是一个糟糕的解决方案,因为 Parent的new Child()实例将返回 false .如果要正确设置原型链,以便进行真实"继承,则应阅读有关伪经典和原型继承的信息.

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.

这篇关于Lo-Dash的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆