【问题标题】:Confusion With Javascript Inheritance与 Javascript 继承混淆
【发布时间】:2016-09-09 18:28:32
【问题描述】:

我对 javascript 继承感到困惑。

考虑以下代码:

function parent(firstname, lastname) {
    this.firstname = firstname || "abc";
    this.lastname = lastname || "def";
}

function child() {
   this.childname = "xys";
}
parent.prototype.Greetings = function () {
    alert("sayhi");
}
child.prototype = Object.create(parent.prototype);
var child1 = new child();

现在,child1 对象是否可以访问 firstnamelastname 属性? 我可以访问Greetings 方法(因为它在原型中)。 如果我尝试访问这些,它会显示为undefined。 必须进行哪些更改才能访问这些变量?

【问题讨论】:

  • 注意:这是Object.create,而不是object.create
  • 感谢@melpomene 的编辑

标签: javascript javascript-inheritance


【解决方案1】:

要访问这些变量需要做哪些更改?

你必须在子构造函数中调用父构造函数:

function child() {
  parent.call(this);
  this.childname = "xys";
}

JavaScript“继承”比其他语言(至少在 ES6 类之前)没有那么神奇(即隐式)。

在您的示例中,您有一个函数parent,它在this 上设置两个属性。但是,您的代码中没有任何地方调用 parent,因此永远不会设置这些属性。

为了设置它们,我们需要将parent 应用到新的child 实例,这是通过调用parent.call(this); 来完成的。

由于parent 接受参数,您可能希望最终通过child 传递它们:

function child(firstname, lastname) {
  parent.call(this, firstname, lastname);
  this.childname = "xys";
}

相关:Benefits of using `Object.create` for inheritance

【讨论】:

  • 这种方法称为构造函数窃取吗? .对于继承,在javascript中我们应该结合原型和构造函数窃取..如果我错了请纠正我
  • @Geeky:我从未听说过。但这与在其他语言(和 ES6)中调用 super() 相同。对于继承来说,必须调用父构造函数是非常典型的。
【解决方案2】:

更好的方法是使用更新的 ES2015 标准。语法更清晰易懂。执行以下操作:

class Parent {
    constructor(firstname, lastname) {
        this.firstname = firstname || "abc";
        this.lastname = lastname || "def";
    }
    greetings() {
        alert("sayhi");
    }
}

class Child extends Parent {
    constructor(){
        super(firstname, lastname);
        this.childname = "xys";
    }
}
var child1 = new child();

关于 ES2015 的信息可以在 https://babeljs.io/docs/learn-es2015/ 找到。 此外,更多关于 javascript 中的类声明的细节可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

【讨论】:

  • 这不行,你必须在子构造函数中调用super(this)
  • 没错,我忘记了super(this)。我更新了答案。
  • 应该是constructor(firstname, lastname) { super(firstname, lastname)
  • 哦,哎呀,没必要通过这个。
  • 没错,参数必须与父构造函数相同。谢谢。我对 js 继承也有点陌生。
猜你喜欢
  • 1970-01-01
  • 2016-05-13
  • 2015-10-12
  • 1970-01-01
  • 2020-01-09
  • 2016-11-19
  • 1970-01-01
  • 2012-09-20
  • 2011-12-30
相关资源
最近更新 更多