美文网首页
01_17.class语法

01_17.class语法

作者: Robyn_Luo | 来源:发表于2017-11-13 11:30 被阅读0次
 <script>
    // 定义了动物类
    class Animal {

        // 这是构造器
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

        // 这个方法相当于以前加到原型上的实例方法
        eat() {
            console.log('吃吧');
        }

        // 这个方法相当于以前加到原型上的实例方法
        run() {
            console.log('跑吧');
        }

        // 这个方法加了static修饰符,就是以前加到类身上的静态方法
        static getAnimal(...arg) {
            return new Animal(...arg);
        }
    }

    var mao = new Animal('猫咪', 5);
    console.log(mao.name);
    console.log(mao.age);
    mao.eat();
    mao.run();

    // 静态方法由类名直接调用
    Animal.getAnimal('宝宝', 8);
    </script>

相关文章

网友评论

      本文标题:01_17.class语法

      本文链接:https://www.haomeiwen.com/subject/uaaamxtx.html