JavaScript中具有多个函数的类

时间:2016-09-25 12:27:14

标签: javascript class module ecmascript-6 prototype

我尝试创建一个可以显示确认窗口或对话框窗体的函数。这两个函数都在同一个窗口中,因此我可以重用这两个函数。

我想它应该像

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.windowprompt()

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

3 个答案:

答案 0 :(得分:0)

您应该使用.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()

答案 1 :(得分:0)

您可以使用函数和new-keyword。这将创建一个可以访问alert和prompt的新对象,而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 :(得分:0)

当你说上课时,你可以看看ES2015,这是新的 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'); }

相关问题