我已经阅读了一些关于多态性的可能文章。但我认为我还没有很好地理解它的含义和重要性。大部分文章都没有说为什么它很重要以及如何在面向对象编程中实现多态行为(当然是在JavaScript中)。
我无法提供任何代码示例,因为我还不知道如何实现它,所以我的问题如下:
- 它是什么?
- 为什么我们需要它?
- 它是如何工作的?
- 我该如何在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);