静态方法-代码演示

静 态 方 法 :

  • 什么是静态方法?
  1. 有 static关键字,表明该方法是一个静态方法。
  2. 需要通过类名来调用, 而不是在实例(this)上调用。
  3. 如果使用this调用,或者在该方法中使用this。 均会出现异常。
  4. 静态方法可以和非静态方法重名 (不推荐这样)。
  5. 父类的静态方法,可以被子类继承。

演示代码:

 <script>
 {

            class Person{
                //实例属性的新写法, 位置放在类的顶部
                num = "我是实例属性的新写法";     
                
                //    
                // 写法: 在实例属性前, 加static关键字
                static Admin = "开机密码";

                constructor(num_a,num_b) {
                    //实例属性
                    //绑定这里可以让全局都能找到
                    this.num_a = num_a;
                    this.num_b = num_b;
                }
                //关键字
                  static sum(){
                    // return this.num_a > this.num_b ? this.num_a : this.num_b; 
                    return "hello";
                }

                newStr(){
                    // return `我是很大的那个${this.sum()}`
                    console.log(`我是很大的那个${Person.sum()}和${this.num}`);
                }
            }

             console.log(Person.sum());
//用new实例化一个对象
            let person = new Person(20,50);
            // console.log(person.sum());
            // console.log(person.newStr());
            person.newStr();
            console.log(Person.Admin);
        }    
   static sum(){
                    // return this.num_a > this.num_b ? this.num_a : this.num_b; 
                    return "hello";
                }

                newStr(){
                    // return `我是很大的那个${this.sum()}`
                    console.log(`我是很大的那个${Person.sum()}和${this.num}`);
                }
            }

             console.log(Person.sum());

            let person = new Person(20,50);
            // console.log(person.sum());
            // console.log(person.newStr());
            person.newStr();
            console.log(Person.Admin);
        }    
       static sum(){
                    // return this.num_a > this.num_b ? this.num_a : this.num_b; 
                    return "hello";
                }

                newStr(){
                    // return `我是很大的那个${this.sum()}`
                    console.log(`我是很大的那个${Person.sum()}和${this.num}`);
                }
            }

             console.log(Person.sum());

            let person = new Person(20,50);
            // console.log(person.sum());
            // console.log(person.newStr());
            person.newStr();
            console.log(Person.Admin);
        }    
  </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值