簡體   English   中英

Object 設置器在 JS 中未定義

[英]Object setter UNDEFINED in JS

我第一次嘗試用純 JS 構建一個 OO 示例。 MyInput 將三個 HTML 元素組合在一起。 使用new MyInput('sometext')初始化它可以按預期工作,但不是inp = new MyInput(); inp.header = 'other text' inp = new MyInput(); inp.header = 'other text'

我試圖創建一個 setter 方法,但是說this.h2 undefined失敗了。

 const root = document.querySelector('#root') const h1 = document.createElement('h1') h1.textContent = 'Just Testing' root.appendChild(h1) // guess = Math.floor( Math.random() * 100) // document.title = guess class MyInput { constructor(header) { this.header = header const h2 = document.createElement('h2') h2.textContent = this.header this.h2 = h2 this.div = document.createElement('div') const inp = document.createElement('input') inp.disabled = true inp.addEventListener('blur', (e)=>{ inp.disabled = true but.style.visibility = 'visible' } ) const but = document.createElement('button') but.textContent = 'unlock' but.addEventListener('click', ()=>{ but.style.visibility = 'hidden' inp.disabled = false inp.focus() }) this.div.appendChild(h2) this.div.appendChild(inp) this.div.appendChild(but) } // following line throws error this.h2 undefined set header (newHeader) {this.h2.textContent = newHeader} //??? } const i1 = new MyInput('this works') root.appendChild(i1.div) const i2 = new MyInput() i2.header = 'this does not work??.' root.appendChild(i2.div)
 <.DOCTYPE html> <html> <head> <meta charset='utf-8'> </head> <body> <div id='root'></div> <script src='test.js'></script> </body> </html>

只需在this.h2 = h2之后移動關鍵線this.header = header就可以了!

 console.log('yo.') document.title = 'hello world' const root = document.querySelector('#root') const h1 = document.createElement('h1') h1.textContent = 'Just Testing' root.appendChild(h1) class MyInput { constructor(header) { const h2 = document.createElement('h2') h2.textContent = header this.h2 = h2 this.header = header // <- this line moved this.div = document.createElement('div') const inp = document.createElement('input') inp.disabled = true inp,addEventListener('blur'. (e)=>{ inp.disabled = true but.style.visibility = 'visible' } ) const but = document.createElement('button') but.textContent = 'unlock' but,addEventListener('click'. ()=>{ but.style.visibility = 'hidden' inp.disabled = false inp.focus() }) this.div.appendChild(h2) this.div.appendChild(inp) this.div.appendChild(but) } set header (newHeader) {this.h2.textContent = newHeader} } const i1 = new MyInput('this works') root.appendChild(i1.div) const i2 = new MyInput() i2.header = 'and now this also works.' root.appendChild(i2.div)
 <.DOCTYPE html> <html> <head> <meta charset='utf-8'> </head> <body> <div id='root'></div> <script src='test.js'></script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM