【问题标题】:Difference between static and normal function inside a class [duplicate]类中静态函数和普通函数之间的区别[重复]
【发布时间】:2019-07-06 21:44:01
【问题描述】:

我以这种方式定义了我的班级

class className {
  constructor() {

  }

  static myStaticFunction() {
    console.log("myStaticFunction")
  }

  normalFunction() {
    console.log("normalFunction")
  }
}

module.exports = className

我知道normalFunction 可以使用instance 调用,而静态函数可以在没有instance 的情况下调用。 但是我需要知道上面两个函数声明有什么区别?

谢谢!!!

【问题讨论】:

    标签: javascript node.js function class


    【解决方案1】:

    当从类本身调用函数时,它被称为static 函数,而普通函数在类的实例上调用

    例如

    class className {
      constructor() {}
    
      static myStaticFunction() {
        console.log("myStaticFunction")
      }
    
      normalFunction() {
        myStaticFunction() // here myStaticFunction is called from same class
        console.log("normalFunction")
      }
    }
    
    module.exports = className
    

    在其他一些js文件中

    import * as class1 from './class';
    class className2 {
          constructor() {}
    
            someFunction() {
            class1 .normalFunction(); //calling class function
            console.log("normalFunction")
          }
        }
    
        module.exports = className2
    

    【讨论】:

      【解决方案2】:

      静态函数 - 无权访问任何对象实例。这意味着该函数可以在没有实例的情况下访问,并且它也无法访问任何实例数据。基本上它有助于公开哪种实用程序的功能。

      正如 MDN 所描述的那样,“调用静态方法时无需实例化 他们的类,并且在类被实例化时也不能调用。 静态方法通常用于创建实用程序函数 应用。”换句话说,静态方法无法访问数据 存储在特定对象中。

      示例:Math.Sqrt(val) - 是 util 函数。

      并且静态函数必须是纯函数,不修改对象数据并提供实用性。

      所以这里是如何工作的

      class className {
        instanceCounter = 0;
        staticCounter = 0;
        constructor() {
      
        }
      
        static myStaticFunction() {
          this.staticCounter++;
          console.log("myStaticFunction"+ staticCounter);
        }
      
        normalFunction() {
          this.instanceCounter++;
          console.log("normalFunction" + instanceCounter);
        }
      }
      

      现在如果我打电话

         //for static   
         className.myStaticFunction();//print 1
         className.myStaticFunction();//print 2
      
         //for instace 
         new className().normalFunction();//print 1
         new className().normalFunction();//print 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-14
        • 2012-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多