博客列表 >类的全面总结

类的全面总结

P粉036614676
P粉036614676原创
2022年07月26日 13:09:12317浏览

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>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议