JavaScript是静态函数

danday74

是否可以确定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

马克·迈耶

函数对自己不了解。当您传递函数引用时,仅是一个函数引用-它无法跟踪谁持有对该函数的引用。使函数成为静态函数的函数本身没有什么特别的。

这可能很脆弱,并且可能存在边缘情况,尤其是当您想扩展类时。如此说来,您可以搜索该类的原型,并查看其属性之一是否包含对所讨论函数的引用:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章