我有以下代码:
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
) 构造函数的双重调用。为了保持清晰,我在构造函数内分配原型(prototype)属性,并为了防止每次创建新实例时发生这种情况,我检查原型(prototype)属性是否存在。如果是这样,那么我们不想重新分配属性,否则我们会这样做。问题是,我收到一个 TypeError,提示“employee.getName 不是函数
”。仅当我尝试使用 Employee 实例访问 Employee 的原型(prototype)属性时才会发生这种情况。 person 构造函数具有相同的方法来分配 Prototype 属性,但它工作得很好。
console.log(person.getName()); // "Dave"
console.log(employee.getSkills()); // or getName or anything, TypeError
我想我在那里做了一些愚蠢的事情,但无法发现它。那么,出了什么问题?
最佳答案
在外部调用inheritPrototype
怎么样?
这对我有用:
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) {
Employee.prototype.getSkills = function () { return this.skills; }
}
}
inheritPrototype(Person, Employee); // <= FIX
var person = new Person ("Dave", 21);
var employee = new Employee ("David", 22, ["C", "C++", "Java", "Python", "PHP"]);
console.log(person.getName()); // returns "Dave"
console.log(employee.getSkills()); // returns ["C", "C++", "Java", "Python", "PHP"]
console.log(employee.getName()); // returns David
关于javascript - 检索原型(prototype)属性时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40211193/