javascript - 检索原型(prototype)属性时出现类型错误

标签 javascript object constructor prototype-programming

我有以下代码:

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/

相关文章:

c++ - 与 get_instance() 分离的单例构造函数

c++ - 如何区分具有相同参数的两个构造函数?

javascript - RMarkdown : Color single cells in an HTML table based on conditions

javascript - 在 php 中隐藏/显示切换回显结果

c++ - 是否可以从 C++ 中的构造函数访问对象名称?

java - 在循环内创建对象好吗?

java - 在java的构造函数中创建的未分配对象的生命周期是多少?

javascript - 使用 jQuery 将值 append 到输入字段

javascript - 了解搜索表单的 jQuery 实现

Java 使用 Comparable、Collections.sort() 对自定义对象进行排序