27_JavaScript之类

在ES6之前,我们是通过构造函数来定义类的

    <script>
        function Person(myName, myAge) {
            this.name = myName;
            this.age = myAge;
            this.say = function() {
                console.log("Hello World");
            }
        }
        let p = new Person("Durant", 30);
        console.log(p);
    </script>

从ES6开始系统提供了一个名称叫做class的关键字, 这个关键字就是专门用于定义类的

    <script>
        class Person {
            constructor(myName, myAge) {
                this.name = myName;
                this.age = myAge;
                this.say = function() {
                    console.log("Hello World");

                }
            }
        }
        let p = new Person("Durant", 30);
        console.log(p);
    </script>

控制台输出:
在这里插入图片描述

如果想要给类的原型对象添加属性和方法,只可通过以下一种方式

    <script>
        class Person {
            constructor(myName, myAge) {
                this.name = myName;
                this.age = myAge;
                this.say = function() {
                    console.log("Hello World");

                }
            }
            run() {
                console.log("run"); //此时run方法是在原型对象中的

            }
        }
        Person.prototype.type = '人';
        Person.prototype.talk = function() { //添加方法也可以模仿run()方法那样实现
            console.log("talk");

        }
        let p = new Person("Durant", 30);
        console.log(p);
    </script>

控制台输出:
在这里插入图片描述

在类中添加静态属性和静态方法:

    <script>
        class Person {
            constructor(myName, myAge) {
                this.name = myName;
                this.age = myAge;
                this.say = function() {
                    console.log("Hello World");

                }
            }
            static talk() { //静态方法
                console.log("123");

            }
        }
        Person.num = 666; // 静态属性

        let p = new Person("Durant", 30);
        console.log(p);
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值