【问题标题】:how to generate a static function without 'class{}'? [duplicate]如何生成没有“类{}”的静态函数? [复制]
【发布时间】:2021-12-30 01:45:44
【问题描述】:

我如何生成类似的东西:

function generator() {
static funct(){}
}

我想我错了,但据我了解class {} 方法是建立在function(){} 之上的,因此它应该具有相同的方法。关键是静态方法没有.prototype,我想知道它们是如何通过class {}创建的

@UPDATE
显然,据我了解,class {} 方法实际上是通过Object() 构建静态函数,因为两者都可以创建静态函数。

class A {
  static a() {}
}

const B = {b(){}};

console.log('a' in A && 'b' in B)
console.log(`${A.a.prototype}, ${B.b.prototype}`);

【问题讨论】:

  • function generator(){}; generator.funct = function(){};
  • @ASDFGerte 它生成一个.prototype,所以它不是一个静态函数
  • 如果您关心所有的小细节,我不确定是否可能。首先,您需要一个没有[[Construct]] 而是non-lexical-this 的函数。在这里调查为时已晚,但听起来很难得到。 Afaik,class 主要是语法糖,但在您想深入细节时,“大部分”并不意味着“可以在 ES5 中完全完全表达”。
  • 你想用这个完成什么?
  • @RafaeldeSouza 这是一个静态方法。它有一个.prototype 属性,那又怎样?这并不意味着它没有功能。如果要创建没有 .prototype 属性且没有 class 语法的方法,请在对象字面量 ({funct(){…}}).funct 中使用方法定义。

标签: javascript


【解决方案1】:

老实说,你能得到的最接近的就是自己删除它:

function generator() {
  if (!(this instanceof TestClass)) throw new TypeError("Cannot call a class as a function");
}

generator.funct = function() {
  console.log(this.funct);  
  return "test";
}

generator.funct.prototype = undefined;

console.log(generator.funct())
console.log(generator.funct.prototoype)

提供与

相同的输出

class generator {
  static funct() {
    console.log(this.funct)
    return "test";
  }
}

console.log(generator.funct())
console.log(generator.funct.prototoype)

但我不明白为什么这是必要的,即使在 Babel 中转译成 ES5 语法时,静态方法仍然有原型。

【讨论】:

    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 2016-07-13
    • 2011-01-07
    • 1970-01-01
    • 2011-12-28
    • 2014-06-13
    • 1970-01-01
    • 2014-11-24
    相关资源
    最近更新 更多