上次代碼中,能夠發現構建兩個進程的代碼幾乎同樣,若須要渲染的進程有不少,對於如下這個代碼塊會出現屢次使用,若是每次都去複製粘貼顯然不現實javascript
mainWindow = new BrowserWindow({ width: 900, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration:true//設置此項以使用nodejs }, frame:false })
所以使用一個封裝類來進行代碼複用html
class AppWindow extends BrowserWindow{//自定義建立窗口的封裝類,繼承於BrowserWindow constructor(config, fileLocation){ const basicConfig = { width: 900, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration:true//設置此項以使用nodejs }, frame:false } const finalConfig1 = Object.assign(basicConfig, config)//將傳入的對象和原來的對象合併 const finalConfig = { ...basicConfig, ...config}//也能夠這樣寫(ES6語法) super(finalConfig)//調用父類的constructor this.loadFile(fileLocation)//調用當前類 //不懂的去看super和this的區別 } }
此時只須要這樣調用java
mainWindow = new AppWindow({}, './renderer/index.html') const addWindow = new AppWindow({ width:500, height:400, parent:mainWindow }, './renderer/ad.html')
同時使用ready-to-show進行一個優化,在AppWindow中添加node
this.once('ready-to-show', ()=>{ this.show() })