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