JavaScript实现多态和继承的封装操作示例

来源:前端全栈君丶 发布时间:2018-12-04 14:01:01 阅读量:1056

封装Encapsulation


如下代码,这就算是封装了


(function (windows, undefined) {

  var i = 0;//相对外部环境来说,这里的i就算是封装了

})(window, undefined);

1

2

3

继承Inheritance


(function (windows, undefined) {

  //父类

  function Person() { }

  Person.prototype.name = "name in Person";

  //子类

  function Student() { }

  Student.prototype = new Person();      //修复原型

  Student.prototype.constructor = Student;  //构造函数

  Student.prototype.supr = Person.prototype; //父类

  //创建子类实例

  var stu = new Student();

  Student.prototype.age = 28;

  Student.prototype.name = "name in Student instance";

  //打印子类成员及父类成员

  console.log(stu.name); //name in Student instance

  console.log(stu.supr.name); //name in Person

  console.log(stu.age); //28

})(window, undefined);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

前端全栈学习交流圈:866109386,面向1-3经验年前端开发人员,帮助突破技术瓶颈,提升思维能力


运行结果如下:


多态Polymorphism


有了继承,多态就好办了


//这就是继承了

(function (windows, undefined) {

  //父类

  function Person() { }

  Person.prototype.name = "name in Person";

  Person.prototype.learning = function () {

    console.log("learning in Person")

  }

  //子类

  function Student() { }

  Student.prototype = new Person();      //修复原型

  Student.prototype.constructor = Student;  //构造函数

  Student.prototype.supr = Person.prototype; //父类

  Student.prototype.learning = function () {

    console.log("learning in Student");

  }

  //工人

  function Worker() { }

  Worker.prototype = new Person();      //修复原型

  Worker.prototype.constructor = Worker;  //构造函数

  Worker.prototype.supr = Person.prototype; //父类

  Worker.prototype.learning = function () {

    console.log("learning in Worker");

  }

  //工厂

  var personFactory = function (type) {

    switch (type) {

      case "Worker":

        return new Worker();

        break;

      case "Student":

        return new Student();

        break;

    }

    return new Person();

  }

  //客户端

  var person = personFactory("Student");

  person.learning(); //learning in Student

  person = personFactory("Worker");

  person.learning(); //learning in Worker

})(window, undefined);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

运行结果如下:


--------------------- 



标签: 环境搭建
分享:
评论:
你还没有登录,请先