zoukankan      html  css  js  c++  java
  • javascript公有静态成员

    公共静态成员
    在javascript中并没有特殊语法来表示静态成员。但是可以通过使用构造函数向其添加属性这种方式。

    //构造函数
    var Gadget = function(){};
    
    //静态方法
    Gadget.isShiny = function(){
      return 'you bet';
    }
    
    //向该原型添加一个普通方法
    Gadget.prototype.setPrice = function(price){
      this.price = price;
    }
    //调用静态方法 console.log( Gadget.isShiny() ); //输出'you bet' //创建一个实例并调用其方法 var iphone = new Gadget(); iphone.setPrice(500); //试图调用构造函数静态方法 iphone.isShiny(); //报错 以上代码可以看错,试图以一个实例方法调用构造函数的静态方法会报错,所以我们需要做一些改动,代码如下: //构造函数 var Gadget = function(price){   this.price = price; }; //静态方法 Gadget.isShiny = function(){   var msg = 'you bet';   //只有实例才会执行   if( this instanceof Gadget ){     msg += ', it costs $' + this.price + '!';   }   return msg; } //向该原型添加一个普通方法 Gadget.prototype.isShiny = function(){   return Gadget.isShiny.call(this); } //静态方法调用 console.log( Gadget.isShiny() ); //输出:'you bet' //测试实例,非静态调用 var a = new Gadget(499.99); console.log( a.isShiny() ); //输出:'you bet, it costs $499.99!'

      

  • 相关阅读:
    js键盘事件
    jq 插件写法
    js 去除字符串空白符
    C# ExpandoObject用法
    C# dynamic与var的区别
    c# 可选参数与命名实参
    C# 扩展方法
    python运算符
    【HDOJ】3006 The Number of set
    【HDOJ】3205 Factorization
  • 原文地址:https://www.cnblogs.com/fengzekun/p/3894448.html
Copyright © 2011-2022 走看看