2016-09-25 10 views
0

私は、確認ウィンドウまたはダイアログフォームを表示できる関数を作成しようとしています。これらの2つの関数は同じウィンドウ内にあるので、両方でコードを再利用するかもしれません。JavaScriptで複数の関数を持つクラス

私はそれは問題は、私はどこのウィンドウを描画するかわからないということです

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クラスを使うべきですか?

+2

これはオブジェクトのように 'MyWindow'関数を使用しています(これは可能ですが)。それを関数の代わりにオブジェクトにする。 – Teemu

+0

'MyWindow'はインスタンスのシングルトンモジュールまたはコンストラクタであるはずですか? – Bergi

+0

はい、ES6クラスを使用する必要があります。 – Bergi

答えて

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

0

を参照してください。これにより、アラートとプロンプトにアクセスできる新しいオブジェクトが作成され、initメソッドは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();

0

クラスを言うときあなたは新しい JavascriptのあるES2015を見ている可能性があります。例を挙げましょう:

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'); }

関連する問題