我已经阅读了一些我可以在互联网上找到的关于多态性的文章。但我想我不能完全理解它的含义和它的重要性。大多数文章都没有说明它为什么重要以及我如何在 OOP 中实现多态行为(当然是在 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);