我试图通过 ES6 类来模拟多态性,以便能够更好地理解这个理论。
概念很清楚(设计对象以共享行为并能够用特定行为覆盖共享行为)但恐怕我上面的代码不是一个有效的多态性示例。
由于我缺乏经验,如果您能全面地回答以下问题,我将不胜感激:
- 事实上,两个类都有一个同样命名的方法,并且每个类创建的实例都可以正确访问它们各自的方法,这使得这是一个多态示例吗?
- 如果这不能模拟多态性,应该进行哪些更改
在代码中做了什么?
- 我试过删除
Employee.prototype = new Person();
线,它仍然有效。这就是为什么我担心我不明白这个概念。
class Person {
constructor (name, age) {
this._name = name;
this._age = age;
}
}
Person.prototype.showInfo = function(){
return "Im " + this._name + ", aged " + this._age;
};
class Employee {
constructor (name, age, sex) {
this._name = name;
this._age = age;
this._sex = sex;
}
}
Employee.prototype = new Person();
Employee.prototype.showInfo = function(){
return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
};
var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');
document.write(myPerson.showInfo() + "<br><br>"); // Im Jon, aged 20
document.write(myEmployee.showInfo() + "<br><br>"); // Im men, named Doe, aged 10
每个 JavaScript 对象都有一个内部“prototype”属性,通常称为 [[prototype]],它指向它直接继承的对象。
每个 JavaScript 函数[对象]都有一个属性原型,它是用一个[几乎]空的对象初始化的。当您通过将其作为构造函数调用来创建该函数的新实例时,该新对象的 [[prototype]] 将指向构造函数的原型对象。
所以,当你写这个的时候var myPerson = new Person('Jon', 20);
,你有方法 showInfo 因为你有这个
Person.prototype.showInfo = function(){
return "Im " + this._name + ", aged " + this._age;
};
使用 ES6,如果你想查看多态性,你可以这样做:
class Person {
constructor (name, age) {
this._name = name;
this._age = age;
}
showInfo () {
return "Im " + this._name + ", aged " + this._age;
}
}
class Employee extends Person {
constructor (name, age, sex) {
super(name,age);
this._sex = sex;
}
showInfo(){
return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
}
}
var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');
document.write(myPerson.showInfo() + "<br><br>"); // Im Jon, aged 20
document.write(myEmployee.showInfo() + "<br><br>"); // Im men, named Doe, aged 10
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)