JavaScript-多态

在看本章节的内容之前你要明确几个东西那么就是什么是强类型语言,什么是是弱类型语言

什么是强类型语言

  • 一般 编译型 语言都是强类型语言
  • 强类型语言,要求变量的使用要严格符合定义
  • 例如定义 int num; 那么 num 中将来就只能够存储整型数据

什么是弱类型语言

  • 一般 解释型 语言都是弱类型语言
  • 弱类型语言,不会要求变量的使用要严格符合定义
  • 例如定义 let num; num 中既可以存储整型,也可以存储布尔类型等等

由于 JS 语言是弱类型的语言,所以我们不用关注多态🐤

什么是多态

多态是指事物的多种状态,例如按下 F1 键这个动作:

  • 如果当前在 webstorm 界面下弹出的就是 webstorm 的帮助文档
  • 如果当前在 Word 下弹出的就是 Word 的帮助文档

同一个事件发生在不同的对象上会产生不同的结果🐱‍👤

多态在编程语言中的体现

父类型变量保存子类型对象,父类型变量当前保存的对象不同,产生的结果也不同,首先来看看模拟其它语言的多态写法,并不能在浏览器中运行会报错只是模拟其它语言请注意,最后会给出JS中的多态写法🌵

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-多态</title>
    <script>
        function Dog() {
            this.eat = function () {
                console.log("狗吃东西");
            }
        }

        function Cat() {
            this.eat = function () {
                console.log("猫吃东西");
            }
        }

        function feed(Dog animal) {
            animal.eat();
        }
        function feed(Cat animal) {
            animal.eat();
        }

        let dog = new Dog();
        feed(dog);

        let cat = new Cat();
        feed(cat);
    </script>
</head>
<body>
</body>
</html>

其实如上代码当中存在问题,现在目前是两个动物,我们就定义了两个喂动物的方法,后面新增了动物也要新增喂动物方法,这显然是不可能的,来看第二种模拟多态的写法注意的是也是其它语言的模拟写法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-多态</title>
    <script>
        function Animal(name) {
            this.name = name;
            this.eat = function () {
                console.log(this.name + "动物吃东西");
            }
        }

        function Dog(name) {
            Animal.call(this, name);
            this.eat = function () {
                console.log("狗吃东西");
            }
        }

        function Cat(name) {
            Animal.call(this, name);
            this.eat = function () {
                console.log("猫吃东西");
            }
        }

        Dog.prototype = new Animal();
        Dog.prototype.constructor = Dog;

        Cat.prototype = new Animal();
        Cat.prototype.constructor = Cat;

        function feed(Animal animal) {
            animal.eat();
        }

        let dog = new Dog();
        feed(dog);

        let cat = new Cat();
        feed(cat);
    </script>
</head>
<body>
</body>
</html>

好了经过如上模拟其它语言的多态之后,在来看看 JS 当中多态如何实现吧,JS 当中的变量有一个特点就是可以保存任意类型的数据那么就可以利用这个特点来实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-多态</title>
    <script>
        function Dog() {
            this.eat = function () {
                console.log("狗吃东西");
            }
        }

        function Cat() {
            this.eat = function () {
                console.log("猫吃东西");
            }
        }

        function feed(animal) {
            animal.eat();
        }

        let dog = new Dog();
        feed(dog);

        let cat = new Cat();
        feed(cat);
    </script>
</head>
<body>
</body>
</html>
posted @ 2021-09-07 15:54  BNTang  阅读(295)  评论(0编辑  收藏  举报