【问题标题】:JavaScript is function staticJavaScript 是静态函数
【发布时间】:2019-05-14 16:08:33
【问题描述】:

是否可以确定 JavaScript 函数是否是静态的?我编写了一个类来测试它,但我需要编写isStatic 方法,它应该返回一个布尔值,显示传入的函数是静态的(返回true)还是不是(返回false)。有人有这方面的代码吗?谢谢

class MyClass {
  static myStaticMethod() {
    return 'hi'
  }
  myMethod() {
    return 'hi'
  }
  isStatic(func) {
    // return a boolean here which shows whether func is static or not
  }
  test1() {
    return this.isStatic(MyClass.myStaticMethod)
  }
  test2() {
    return this.isStatic(this.myMethod)
  }
}

const obj = new MyClass()
console.log(obj.test1()) // should return true - currently returns undefined
console.log(obj.test2()) // should return false - currently returns undefined

【问题讨论】:

  • 为什么需要在运行时确定这一点?
  • 我正在使用 JavaScript 装饰器。装饰函数必须是纯函数。由于不可能轻易确定一个函数是否是纯函数,我的想法是强制装饰函数是静态的。这是因为静态函数大多都是纯函数(除非您在其中添加 Math.random 语句)。这是为了保护开发者免受自身伤害。

标签: javascript static


【解决方案1】:

函数本身并不“了解”这一点。当你传递一个函数引用时,它只是一个函数引用——它不会跟踪谁持有对它的引用。使其成为静态函数的函数本身并没有什么特别之处。

这可能很脆弱,并且可能存在边缘情况,尤其是当您想要扩展类时。话虽如此,您可以搜索类的原型,看看它的一个属性是否包含对相关函数的引用:

class MyClass {
  static myStaticMethod() {
    return 'hi'
  }
  myMethod() {
    return 'hi'
  }
  isStatic(func) {
    // return a boolean here which shows whether func is static or not
    for (let name of Object.getOwnPropertyNames(MyClass)) {
      if (func === MyClass[name])
        return true
    }
    return false
  }
  test1() {
    return this.isStatic(MyClass.myStaticMethod)
  }
  test2() {
    return this.isStatic(this.myMethod)
  }
}

const obj = new MyClass()
console.log(obj.test1()) // should return true - currently returns undefined
console.log(obj.test2()) // should return false - currently returns undefined

isStatic 本身是一个静态函数可能更有意义。然后你可以避免将类名硬编码到方法中:

class MyClass {
  static myStaticMethod() {
    return 'hi'
  }
  myMethod() {
    return 'hi'
  }
  static isStatic(func) {
    // return a boolean here which shows whether func is static or not
    for (let name of Object.getOwnPropertyNames(this)){
      if (func === this[name]) 
        return true
    }
    return false
  }
  test1() {
    return Object.getPrototypeOf(this).constructor.isStatic(MyClass.myStaticMethod)
  }
  test2() {
    return  Object.getPrototypeOf(this).constructor.isStatic(this.myMethod)
  }
}

const obj = new MyClass()
console.log(obj.test1()) // should return true - currently returns undefined
console.log(obj.test2()) // should return false - currently returns undefined

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2016-05-11
    相关资源
    最近更新 更多