多态性JavaScript中的示例用法错误

时间:2016-08-25 05:38:58

标签: javascript function oop polymorphism

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

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

对程序仍然没有影响,它得到了类似的结果。如果是这样,这个例子如何演示多态?在评论这些行时,我看到有两个函数在调用返回结果时基于他们自己的 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>

结果

enter image description here

参考

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

2 个答案:

答案 0 :(得分:1)

这实际上是多态性的一个弱例子,除了你注意到的问题(即Employee.prototype设置是超级的,原型函数从未在示例中使用过),这里有一些我看到的其他问题:

  1. Employee函数(即构造函数)从不调用'基类'构造函数,即Person函数 - 假设它们处于父子关系中,您会期望这样。
  2. 由于上述问题,Employee函数已从Parent函数复制粘贴代码:

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

  3. getInfo函数的同意 - 两个构造函数都创建其特定函数并将其分配给this;并且Employee getInfo版本的getInfo永远不会调用基类版本 - 它可能应该展示继承

    所以,真正唯一可以说是支持这个例子的是它在PersonEmployee上使用相同的函数名称STRING mt; (W{REGEXP("myregex1")} W{REGEXP("myregex2")}) { -> MATCHEDTEXT(mt), CREATE(MyType, "label"=mt)}; 并在两者上调用它们使用通用代码的对象。这可以被称为多态的一个例子,但可能是一个基本的

答案 1 :(得分:1)

继承&#34;方法&#34;

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

当执行一个继承的函数时,它的值指向继承对象,而不是指向函数所属属性的原型对象。

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

中找到您要查找的内容