【发布时间】:2016-10-24 05:21:38
【问题描述】:
我有以下代码:
function inheritPrototype (sup, sub) {
var proto = Object.create(sup.prototype);
Object.defineProperty(proto, "constructor", {value : sub});
sub.prototype = proto;
}
function Person (name, age) {
this.name = name;
this.age = age;
if (!Person.prototype.getName) {
Person.prototype.getName = function () { return this.name; }
Person.prototype.getAge = function () { return this.age; }
}
}
function Employee (name, age, skills) {
Person.call(this, name, age);
this.skills = skills;
if (!Employee.prototype.getSkills) {
inheritPrototype(Person, Employee);
Employee.prototype.getSkills = function () { return this.skills; }
}
}
var person = new Person ("Dave", 21);
var employee = new Employee ("David", 22, ["C", "C++", "Java", "Python", "PHP"]);
console.log(employee.getSkills());
inheritPrototype 只是为了防止父 (Person) 构造函数的双重调用而定义的。为了清楚起见,我在构造函数中分配原型属性并防止每次创建新实例时发生这种情况,我正在检查原型属性是否存在。如果是这样,那么我们不想重新分配属性,否则我们会这样做。问题是,我收到一个 TypeError 说“employee.getName is not a function”。仅当我尝试使用 Employee 实例访问 Employee 的原型属性时才会发生这种情况。 person 构造函数具有相同的分配 Prototype 属性的方法,但它工作正常。
console.log(person.getName()); // "Dave"
console.log(employee.getSkills()); // or getName or anything, TypeError
我想我在那里做了一些愚蠢的事情,但无法发现它。那么,怎么了?
【问题讨论】:
-
为什么需要inheritPrototype方法?你能详细说明一下吗? “为了清楚起见,我在构造函数中分配原型属性并防止每次创建新实例时发生这种情况,我正在检查原型属性是否存在。”
-
@Sreekanth 我不想调用 Person 构造函数两次。相反,如果我一直这样做
Employee.prototype = new Person (),我会调用构造函数两次。我使用的模式是Parasitic Combination Inheritance。 -
大家有什么建议吗?
-
我需要先查看寄生组合继承,然后才能发表评论。但是,您在 Employee 上看到错误但在 Person 上没有看到错误的原因是对 Employee 上的 inheritPrototype 进行了调用。
标签: javascript object constructor prototype-programming