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