热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ES6Classes执行多态的能力

如何解决《ES6Classes执行多态的能力》经验,为你挑选了1个好方法。

我试图通过ES6类来模拟多态性,以便能够更好地理解这个理论.

概念很明确(设计对象以共享行为并能够覆盖特定行为的共享行为)但我担心上面的代码不是有效的多态性示例.

由于我缺乏经验,如果您以全面的方式回答这些问题,我将不胜感激:

事实上,两个类都有一个同名的方法,并且每个类的实例都能正确访问它们各自的方法,这使得这个多态的例子?

如果这不能模仿polimorphism,那么应该在代码中做些什么改变呢?

我已经尝试删除该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() + "

"); // Im Jon, aged 20 document.write(myEmployee.showInfo() + "

"); // Im men, named Doe, aged 10



1> geo..:

每个Javascript对象都有一个内部的"prototype"属性,通常称为[[prototype]],它指向它直接继承的对象.

每个Javascript函数[object]都有一个属性原型,用一个[几乎]空对象初始化.当您通过将其作为构造函数调用来创建此函数的新实例时,该新对象的[[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() + "

"); // Im Jon, aged 20 document.write(myEmployee.showInfo() + "

"); // Im men, named Doe, aged 10

推荐阅读
author-avatar
夜冷
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有