【发布时间】: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>
结果
参考
【问题讨论】:
标签: javascript function oop polymorphism