es6之class类

2019-07-09  本文已影响0人  关耳木南
<script type="text/javascript">
    /*
        class 在es6中用于定义类
     */
    //es5写法
    function Person(name,age){
        this.name = name,
        this.age = age
    }
    Person.prototype = {
        sayName(){alert(this.name)},
        sayAge(){alert(this.age)}
    }
    const obj = new Person("fy",18);
    //es6写法
    class Person2{  //类名叫做Person2
        //私有属性  写在constructor中
        constructor(name,age){
            this.name = name,
            this.age = age
        }
        //constructor之外的就是共有方法
        sayName(){alert(this.name)}//可以不用写任何符号
        sayAge(){alert(this.age)}
    }
    const obj2 = new Person2("kobo",20)
    obj.sayName();//fy
    obj2.sayName();//kobo
</script>
上一篇 下一篇

猜你喜欢

热点阅读