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!'

  

原文地址:https://www.cnblogs.com/fengzekun/p/3894448.html