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

      

  • 相关阅读:
    shell 脚本语法
    discuz pre_forum_postposition表说明
    PHP调试工具Xdebug安装配置教程
    检查用户头像状态的脚本
    PHP 性能监测
    Mysql 索引优化
    MySQL主从复制配置
    vue mixin 混入
    vue渲染方式:render和template的区别
    vue自定义指令directive Vue.directive() directives
  • 原文地址:https://www.cnblogs.com/fengzekun/p/3894448.html
Copyright © 2011-2022 走看看