【问题标题】:Javascript. What is the functional equivalent for class constructors?Javascript。类构造函数的功能等价物是什么?
【发布时间】:2022-01-23 09:26:57
【问题描述】:

类构造函数在类中初始化和创建对象/函数。如果我使用函数,我将如何在函数中初始化函数?

这是一个简单的类

export default class MainProcess{
    constructor() {
                 this.isReady = false
        this.init()
         

    }
    init() {
        this.setupApplicationMenu()
        this.initWindowManager()
        this.getIcons()
    }

}

如何启动 MainPROcess 函数?

【问题讨论】:

    标签: node.js class functional-programming


    【解决方案1】:

    函数是类的一部分。类是一组函数(方法)和数据(作为属性)。这些函数用于修改属性。

    在上面的示例中,您创建了一个类MainProcess,其中包含一些功能。但是,init 方法中定义的函数不存在。编译器会报错。

    constructor 是一种特殊方法,用于使用该类创建对象。

    如果我使用函数,我将如何在 功能?

    您似乎在 JS 和稍后介绍的类中混合了两个概念函数构造函数。类什么都不是,只是函数构造函数的语法糖。 JS 是一种基于原型的语言。

    黑白函数和函数构造函数的区别?

    使用 Function 构造函数创建的函数不会为其创建上下文创建闭包;它们总是在全局范围内创建。运行它们时,它们将只能访问自己的局部变量和全局变量,而不能访问创建 Function 构造函数的范围内的变量。这不同于将 Global_Objects/eval 与函数表达式的代码一起使用。

    var x = 10;
    
    function createFunction1() {
        var x = 20;
        return new Function('return x;'); // this |x| refers global |x|
    }
    
    function createFunction2() {
        var x = 20;
        function f() {
            return x; // this |x| refers local |x| above
        }
        return f;
    }
    
    var f1 = createFunction1();
    console.log(f1());          // 10
    var f2 = createFunction2();
    console.log(f2());          // 20
    

    我强烈建议你先了解一下JS是如何在其中实现class的。

    【讨论】:

      【解决方案2】:

      虽然我不完全确定我理解了这个问题,但我想你是在问“我如何才能以类似于我习惯于编写类的方式创建一个函数,但不使用 class关键词?”这是一个例子:

      function Example () {
        this.value = 10;
      
        // instance method
        this.print = function () {
          console.log(this.value);
        }
      }
      
      // static method
      Example.printHello = function () {
        console.log('hello world');
      }
      
      const example1 = new Example();
      example1.print(); // 10
      example1.value = 20;
      example1.print(); //20
      
      console.log(Object.getPrototypeOf(example1).constructor.name); // "Example"
      
      const example2 = new Example();
      example2. print(); //10
      
      Example.printHello(); // "hello world"

      【讨论】:

      • 这就是我想要问的。谢谢——
      猜你喜欢
      • 1970-01-01
      • 2011-04-13
      • 2011-10-14
      • 1970-01-01
      • 2021-08-14
      • 2017-12-07
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多