這是用來證實多態性例如,在其中如果刪除下面的行的一個示例:多態性實施例使用誤差在JavaScript
Employee.prototype= new Person();
Employee.prototype.constructor=Employee;
仍有上的程序沒有影響,它得到了類似的結果。如果是這樣,這個例子是如何展示多態的?評論這些行時,我看到有2個函數,它們在調用返回結果時基於自己的getInfo函數;那麼,魔法在哪裏?
HTML:
<script type="text/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);
</script>
結果
參考
http://w3processing.com/index.php?subMenuItemId=329
這將是巨大的,如果你可以添加一個小提琴或提供一個合理的例子來學習的JS多態性行爲。請幫忙! – Deadpool
請參閱[這篇文章](http://stackoverflow.com/questions/39117168/how-to-properly-subclass-a-subclass-in-javascript)討論基於原型的多態性。 [這個小提琴](https://jsfiddle.net/6x0agapd/)修復了上述文章中討論的代碼,並且是多態性的一個工作示例。 – Dhananjay