• 类定义


    class Chameleon {
      static colorChange(newColor) {
        this.newColor = newColor;
      }
    
      constructor({ newColor = "green" } = {}) {
        this.newColor = newColor;
      }
    }
    
    const freddie = new Chameleon({ newColor: "purple" });
    freddie.colorChange("orange");
    • A: orange

    • B: purple

    • C: green

    • D: TypeError

    colorChange方法是静态的。 静态方法仅在创建它们的构造函数中存在,并且不能传递给任何子级。 由于freddie是一个子级对象,函数不会传递,所以在freddie实例上不存在freddie方法:抛出TypeError

    答案: D

    练习

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 
     4 <head>
     5   <meta charset="UTF-8">
     6   <meta name="viewport" content="width=device-width, initial-scale=1.0">
     7   <meta http-equiv="X-UA-Compatible" content="ie=edge">
     8   <title></title>
     9 </head>
    10 
    11 <body>
    12 <div id="div">2233</div>
    13 </body>
    14 
    15 </html>
    16 <script type="text/javascript">
    17   class Chameleon {
    18     static colorChange(newColor) {
    19       this.newColor = newColor;
    20       return this.newColor
    21     }
    22     constructor({ newColor = "green" } = {}) {
    23       this.newColor = newColor;
    24     }
    25   }
    26   const freddie = new Chameleon({ newColor: "purple" });
    27   console.log(freddie)
    28   console.log(Chameleon.colorChange(freddie.newColor))
    29   freddie.colorChange("orange");
    30 </script>
    index.html

    个人总结:

    这里主要是查看对于类的静态方法的调用,文档的说明是:static 关键字用来定义一个类的一个静态方法。调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。通俗来说就是:不能通过一个类实例调用静态方法

    文档中的案例:

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    
        static distance(a, b) {
            const dx = a.x - b.x;
            const dy = a.y - b.y;
    
            return Math.hypot(dx, dy);
        }
    }
    
    const p1 = new Point(5, 5);
    const p2 = new Point(10, 10);
    
    console.log(Point.distance(p1, p2));

    文档

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes

  • 相关阅读:
    闭包 (Closure)
    RSA算法
    HTTPS
    SSH
    HDU1754 I hate it_线段树(入门级别)
    HDU1166 敌兵布阵_线段树
    c++运算符优先级表
    归并排序练习.
    HDU 1969 精度二分
    uva10944 状态压缩bfs or DP
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/11088846.html
Copyright © 2020-2023  润新知