【问题标题】:Polymorphism Example usage error in JavaScriptJavaScript 中的多态性示例使用错误
【发布时间】:2025-12-17 18:40:02
【问题描述】:

这是一个演示多态性示例的示例,如果我删除以下行:

Employee.prototype= new Person();
Employee.prototype.constructor=Employee;

对程序仍然没有影响,并且得到了类似的结果。如果是这样,这个例子如何证明多态性?评论这些行,我看到有 2 个函数在调用时根据它们自己的 getInfo 函数返回结果;那么,魔法在哪里?

HTML:

<script type="text/javascript">
  function Person(age, weight) {
    this.age=age;
    this.weight=weight;
    this.getInfo=function() {
      return "I am " + this.age + " years old " +
        "and weighs " + this.weight +" kilo.";
    }
  }
  function Employee(age, weight, salary){
    this.salary=salary;
    this.age=age;
    this.weight=weight;
    this.getInfo=function() {
      return "I am " + this.age + " years old " +
        "and weighs " + this.weight +" kilo " +
        "and earns " + this.salary + " dollar.";
    }
  }
  Employee.prototype= new Person();
  Employee.prototype.constructor=Employee;
// The argument, 'obj', can be of any kind
// which method, getInfo(), to be executed depend on the object
// that 'obj' refer to.
  function showInfo(obj) {
    document.write(obj.getInfo()+"<br>");
  }
  var person = new Person(50,90);
  var employee = new Employee(43,80,50000);
  showInfo(person);
  showInfo(employee);
</script>

结果

参考

http://w3processing.com/index.php?subMenuItemId=329

【问题讨论】:

    标签: javascript function oop polymorphism


    【解决方案1】:

    这确实是多态性的一个弱示例,除了您注意到的问题(即Employee.prototype setup 是多余的,示例中从未使用原型函数),还有我看到的其他几个问题:

    1. Employee 函数(即构造函数)从不调用“基类”构造函数,即 Person 函数 - 鉴于它们处于父子关系中,您会认为这是适当的。
    2. 由于上述问题,Employee 函数具有从Parent 函数复制粘贴的代码:

      this.salary=salary; this.age=age; this.weight=weight;

    3. getInfo 函数的同义词 - 两个构造函数都创建它们的特定函数并将其分配给 thisgetInfoEmployee 版本从不调用基类版本——它可能应该这样做,以演示继承

      所以,真正支持这个示例的唯一一点是,它在PersonEmployee 上使用相同的函数名称,即getInfo,并使用通用代码在两个对象上调用它们。可以称为多态性的一个例子,但可能是一个基本的例子

    【讨论】:

    • 如果您可以添加一个小提琴或提供一个合理的示例来学习 JS 中的多态行为,那就太好了。请帮忙!
    • 有关基于原型的多态性的讨论,请参阅this postThis fiddle 修复了上面帖子中讨论的代码,是多态性的一个工作示例。
    【解决方案2】:

    继承“方法”

    JavaScript 没有基于类的语言定义的“方法”。在 JavaScript 中,任何函数都可以以属性的形式添加到对象中。继承函数的作用与任何其他属性一样,包括如上所示的属性阴影(在这种情况下,是一种方法覆盖)。

    当一个继承的函数被执行时,this的值指向继承对象,而不是函数为自己属性的原型对象。

    var o = {
          a: 2,
          m: function(b){
            return this.a + 1;
          }
        };
    
        console.log(o.m()); // 3
        // When calling o.m in this case, 'this' refers to o
    
        var p = Object.create(o);
        // p is an object that inherits from o
    
        p.a = 4; // creates an own property 'a' on p
        console.log(p.m()); // 5
        // when p.m is called, 'this' refers to p.
        // So when p inherits the function m of o, 
        // 'this.a' means p.a, the own property 'a' of p
    

    你可以在 MDN LINK找到你要找的东西

    【讨论】: