js静态属性和静态方法

啥也不说了,直接上代码。。。(就是这么任性)

     var Animal =  function(){};
    Animal.name = "dog";
     var a =  new Animal();

    console.log(a.name); 

结果如图 :

 

很明显这样调用是不可以的,那如果console.log(Animal.name)这样呢?

     var Animal =  function(){
        Animal.name++;
    };
    Animal.name = 0;
     //  var a = new Animal();

    console.log(Animal.name); 

 

 静态方法是指不需要声明类的实例就可以使用的方法

 纳尼?结果是这样了滴。。。。。为毛?

 那这样呢?

      function Animal (){
         //  alert(Animal.name);
         this.say =  function(){
            console.log(Animal.name);
        }
    };
    Animal.name = "Ev2le0";
     var a =  new Animal();

    a.say(); 

结果是:

 

纳尼,哭晕在wc了。。。 

 

算了还是写静态方法吧 

     function staticClass(){}; // 声明一个类
     // 为这个类添加一个静态方法
    staticClass.staticMethod =  function(){
        console.log("this is a static method");
    }

     // 声明一个实例方法
    staticClass.prototype.instanceMethod =  function(){
        console.log("this is a instance method");
    }

     // 尝试调用一下静态方法,分别使用2种方式
     var a =  new staticClass();

    a.staticMethod(); 

 结果是这样滴:

 

 再试一下类名.方法名的调用方式

     function staticClass(){}; // 声明一个类
     // 为这个类添加一个静态方法
    staticClass.staticMethod =  function(){
        console.log("this is a static method");
    }

     // 声明一个实例方法
    staticClass.prototype.instanceMethod =  function(){
        console.log("this is a instance method");
    }

     // 尝试调用一下静态方法,分别使用2种方式
     var a =  new staticClass();
     //  a.staticMethod();

    staticClass.staticMethod();

 结果是这样子滴:

 

 那调用实例方法能不能用类名.方法名()的形式呢?

     function staticClass(){}; // 声明一个类
     // 为这个类添加一个静态方法
    staticClass.staticMethod =  function(){
        console.log("this is a static method");
    }

     // 声明一个实例方法
    staticClass.prototype.instanceMethod =  function(){
        console.log("this is a instance method");
    }

     // 尝试调用一下静态方法,分别使用2种方式
     var a =  new staticClass();
     //  a.staticMethod();

    staticClass.instanceMethod(); 

 结果是这样子滴:

 

 总结:

1,对于静态方法可以使用类名.方法名()

2,实例方法就只能老老实实的使用对象.方法名()的形式调用了。 

 

转载于:https://www.cnblogs.com/EvileOn/p/5515216.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值