JavaScript中ES6中类的定义与使用

    科技2025-07-10  14

    class =》类 object =>对象 构造函数=>用来模拟类的函数 es6以后可以使用class来定义类,然后用类来定义对象

    实例

    <script> //class =》类 object =>对象 //构造函数=>用来模拟类的函数 //es6以后可以使用class来定义类,然后用类来定义对象 var methodName = "smoke" var proper = "height"//定义类使用方法二 class People{//名后面不要打括号 constructor(obj){ this.name = obj.name; this.age = obj.age; this.sex = obj.sex; this.weight = obj.weight; this[proper] = obj.height;//这里传进来height } eat(){//类中定义方法不需要打function console.log(this.name+"is eating"); } study(){ console.log(this.name + " is study") this.weight--; } } var p1 = new People({ name:"张三", age:33, sex:"male", weight:100 }); p1.eat(); console.log(p1.weight); p1.study(); console.log(p1.weight); console.log(p1); console.log(People); console.log(p1.__proto__) p1.__proto__.score = 99;//这种方式可以修改定义该对象的类, //而且将会影响所有使用该类定义的对象,不推荐使用 //---------定义类方法二 var p2 = new People({ name:"李四",age:30,sex:"female",weight:80,height:170 }) console.log(p2.score); p2.smoke(); console.log(p2.height); </script>
    Processed: 0.012, SQL: 8