【问题标题】:Class with multiple functions in JavaScriptJavaScript 中具有多个函数的类
【发布时间】:2016-09-25 12:27:13
【问题描述】:

我尝试制作一个可以显示确认窗口或对话框表单的功能。这两个函数都在同一个窗口中,所以我可能会重复使用这两个函数中的代码。

我想应该是这样的

const MyWindow = function (options) {
};

MyWindow.prompt = function (options) {
  ..
};

MyWindow.confirm = function (options) {
  ...
}

MyWindow.alert = function (options) {
  ...
}

问题是我不知道在哪里绘制窗口。

我已经尝试创建一个新方法

const MyWindow = function (options) {
};

MyWindow.createElements = function (options) {
  this.window = document.createElement('div');
  this.window.style.height = 300;
  this.window.style.width = 300;
  document.body.insertBefore(this.window, document.body.childNodes[0]);
};

MyWindow.prompt = function (options) {
  this.createElements();
  this.window.style.background-color = 'red';
};

this.createElements()this.window 无法从prompt() 函数访问。

你通常如何开发这样的东西?我应该使用 ES6 类吗?

【问题讨论】:

  • 您正在使用MyWindow 函数,就像它是一个对象一样(虽然这是可能的)。让它成为一个对象而不是函数。
  • MyWindow 应该是单例模块还是实例的构造函数?
  • 是的,你应该使用 ES6 类。

标签: javascript class module ecmascript-6 prototype


【解决方案1】:

您可以使用函数和新关键字。这将创建一个可以访问警报和提示的新对象,而 init-method 对于 MyWindow 是私有的。

const MyWindow = function() {
  const init = () => console.log("do init stuff");

  this.alert = () => {
    init();
    console.log("alert!");
  };

  this.prompt = () => {
    init();
    console.log("prompt");
  }
}

const myWindow = new MyWindow();

myWindow.alert();
myWindow.prompt();

【讨论】:

    【解决方案2】:

    您应该使用.prototype 来扩展一个类。这应该可以帮助您...

    参考this link

    var MyWindow = function (options) {
    }
    
    MyWindow.prototype.createElements = function (options) {
      this.window = document.createElement('div');
      this.window.style.height = '300px';
      this.window.style.width = '300px';
      document.body.insertBefore(this.window, document.body.childNodes[0]);
    };
    
    MyWindow.prototype.prompt = function (options) {
      this.createElements();
      this.window.style.backgroundColor = 'red';
    }
    
    var el = new MyWindow()
    el.prompt()

    【讨论】:

      【解决方案3】:

      当你说类时,你可以看看 ES2015,它是 new Javascript。举个例子吧:

      class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log('Hello ' + this.name + ' wow you are ' + this.age + ' years old'); } }

      我会在控制台日志中的上述示例中使用 ES2015 literals,但我不能在这里执行此操作,或者我可以吗?

      要使用上面的类,你只需这样做:

      const person = new Person('Jack', 21)

      person.sayHello()

      输出 - 你好,杰克哇,你 21 岁了

      这是一个例子,你会用一些方法在 ES2015 中编写一个类。如果您想以较旧的方式将方法添加到“类”,您只需执行以下操作:

      function Person(name, age) { this.name = name; this.age = age; }

      要添加一个方法(扩展)你的函数,你只需要像这样使用原型:

      Person.prototype.sayHello = function() { console.log('Hello ' + this.name + ' wow you are ' + this.age + ' years old'); }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        • 1970-01-01
        • 2022-01-23
        • 2016-09-05
        • 2011-02-01
        相关资源
        最近更新 更多