【发布时间】: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 对象是否可以访问 firstname 和 lastname 属性?
我可以访问Greetings 方法(因为它在原型中)。
如果我尝试访问这些,它会显示为undefined。
必须进行哪些更改才能访问这些变量?
【问题讨论】:
-
注意:这是
Object.create,而不是object.create。 -
感谢@melpomene 的编辑
标签: javascript javascript-inheritance