![](/img/trans.png)
[英]How do I apply Javascript functions to multiple instances of a class?
[英]Class with multiple functions in 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
無法從this.window
prompt()
函數訪問。
您通常如何開發這樣的東西? 我應該使用ES6類嗎?
您應該使用.prototype
擴展類。 這應該可以幫助您...
引用此鏈接
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()
您可以使用函數和新關鍵字。 這將創建一個具有警報和提示訪問權限的新對象,而初始化方法是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();
當您說上課時,您可以看看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 文字 ,但是我不能在此處執行此操作,或者可以嗎?
要使用上面的類,您只需執行以下操作:
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'); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.