2016-09-25 25 views
0

我嘗試創建一個可以顯示確認窗口或對話框窗體的函數。這兩個函數都在同一個窗口中,所以我可能會重用兩者中的代碼。在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
當你說類,你可以看看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'); }