博主信息
博文 47
粉丝 0
评论 0
访问量 31360
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
类的全面总结
P粉036614676
原创
463人浏览过

1.对象字面量

  1. <script>
  2. // 1.对象字面量
  3. let item = {
  4. data:{
  5. name:'asd',
  6. price:5000
  7. },
  8. getPrice(){
  9. return this.data.price;
  10. },//接口函数
  11. setPrice(x){
  12. this.data.price = x;
  13. }
  14. }
  15. console.log(item.data.price);
  16. console.log(item.getPrice());
  17. // 追加字面量
  18. let student = {}
  19. student.x = 100;
  20. student.y = 200;//设置变量
  21. student.getPrice = function (x){
  22. this.y = x;
  23. }//设置函数
  24. // console.log(student);
  25. student.getPrice(300);
  26. console.log(student);
  27. </script>

总结:对象字面量,要么一次性设置全部属性,要么
一个一个添加;

  1. <script>
  2. //访问器属性
  3. let student={
  4. data:{
  5. name:'ajs',
  6. price:200
  7. },
  8. name(x){
  9. this.data.name = x
  10. },
  11. name(){
  12. return this.data.name;
  13. }
  14. }
  15. // 访问器属性
  16. console.log(student.name());
  17. </script>

2.构造函数

  1. <script>
  2. //构造函数一定是function(){}
  3. let user = function(name,price){
  4. this.name = name;
  5. this.price = price;
  6. this.getValue = () => {
  7. console.log(this.name);
  8. };
  9. };
  10. // user.prototype.getValue = () =>{
  11. // console.log(`${this.name}:${this.value}`);
  12. // }
  13. let User1 = new user('as',200);
  14. User1.getValue();
  15. </script>

继承:

  1. <script>
  2. //继承,构造函数都用function(){}
  3. let Parent = function(){};
  4. Parent.prototype.sum = function() {
  5. console.log(this.a);
  6. };
  7. let Child = function (a, b) {
  8. this.a = a;
  9. this.b = b;
  10. };
  11. Child.prototype = Parent.prototype;
  12. let child = new Child(100, 200);
  13. child.sum();
  14. </script>

3.类

  1. //申明类
  2. class student{
  3. constructor(name,value){
  4. this.name = name;
  5. this.value = value;
  6. };
  7. getSum(){
  8. console.log(`${this.value}`);
  9. };
  10. } ;
  11. let student1 = new student('12',23);
  12. student1.getSum();
  13. //继承
  14. class teacher extends student{
  15. constructor(name,value,sex){
  16. super(name,value);
  17. this.sex = sex;
  18. }
  19. getx(){
  20. console.log(this.sex);
  21. }
  22. }
  23. let teachers = new teacher('12',23,34);
  24. </script>

4.结构赋值

4.1数组解构

  1. <script>
  2. //数组解构
  3. let [a,b,c] = [1,2,3];
  4. console.log(a,b,c);
  5. let [x,...y] = [1,2,3,4,5];
  6. console.log(x,y);
  7. </script>

4.2对象解构

  1. <script>
  2. function f({name,value})
  3. {
  4. console.log(name,value);
  5. };
  6. let student={
  7. name:'as',
  8. value:120
  9. };
  10. f(student);
  11. </script>
批改老师:PHPzPHPz

批改状态:合格

老师批语:构造函数名一般使用首字母大写形式
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学