我读过一些我可以在互联网上找到的关于多态的文章。但是我认为我不太了解它的含义及其重要性。大多数文章都没有说明为什么它很重要,以及如何在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);