【问题标题】:Is it Possible to Write Class Functions when Declaring a Class? [duplicate]声明类时是否可以编写类函数? [复制]
【发布时间】:2021-07-02 23:42:10
【问题描述】:

假设你有 Foo 类

class Foo {
    constructor(name) {
        this.name = name;
    }
    sayName() {
        console.log('My name is ' + this.name);
    }
}

可能有像 'sayName' 这样的实例函数

  new Foo('Kevin').sayName() // My name is Kevin

但我想要一个类函数。

我可以这样做: 即。

  Foo.sayClassName = () => console.log('My Name is Foo')
  Foo.sayClassName() // 'My Name is Foo'

但我想在声明课程时声明这一点。这可能吗?

【问题讨论】:

  • static sayClassName() { console.log(`My Name is ${this.name}`); }

标签: javascript node.js


【解决方案1】:

您可以使用static 方法。

class Foo {
    constructor(name) {
        this.name = name;
    }
    sayName() {
        console.log('My name is ' + this.name);
    }
    static sayClassName(){
      console.log('My Name is Foo');
    }
}
Foo.sayClassName();

【讨论】:

    【解决方案2】:

    是的,如果成员函数是static

    class Foo {
      constructor(name) {
        this.name = name;
      }
      static sayName() {
        console.log("sayName() called");
      }
    }
    
    Foo.sayName()

    【讨论】:

      【解决方案3】:

      静态方法

      静态方法是直接在类对象(原型的父级)上的方法,并且允许这种行为。为此,请在方法前加上“静态”。 MDN: Classes/static

      static 关键字定义类的静态方法或属性。不能在类的实例上调用静态方法和静态属性。相反,它们是在类本身上调用的。

      静态方法通常是实用函数,例如创建或克隆对象的函数,而静态属性对于缓存、固定配置或任何其他不需要跨实例复制的数据很有用。

      class Foo {
          constructor() {}
          static bar() { console.log('called'); }
      }
      
      Foo.bar(); // prints 'called'
      

      复制行为

      JS 类只是具有原型的对象。例如:

      // class Foo {
      //     constructor(name) { console.log('Defined: ' + name); this.name = name; }
      //     static staticFunc() { console.log('[static]'); }
      //     method() { console.log(this.name); }
      // }
      
      let Foo = function(name) { console.log('Defined: ' + name); this.name = name; }
      Foo.staticFunc = function() { console.log('[static]'); }
      Foo.prototype = { method: function() { console.log(this.name); } }
      

      【讨论】:

        猜你喜欢
        • 2020-03-05
        • 2019-09-21
        • 2016-05-07
        • 2015-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        相关资源
        最近更新 更多