类定义

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

转载于:https://www.cnblogs.com/wang715100018066/p/11088846.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值