JS中的对象设置器未定义
Posted
技术标签:
【中文标题】JS中的对象设置器未定义【英文标题】:Object setter UNDEFINED in JS 【发布时间】:2022-01-23 12:35:03 【问题描述】:我第一次尝试用纯 JS 构建一个 OO 示例。 MyInput 将三个 html 元素组合在一起。使用new MyInput('sometext')
初始化它可以按预期工作,但不是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.header = header
开头,但 this.h2
仅在该行之后添加。因此,当 setter 尝试访问 this.h2
时,它永远不会在那里。
我明白了,评论这条线很有帮助!
离题,因为您正尝试从头开始构建自定义 DOM 元素。我建议你看看custom element
【参考方案1】:
只需在 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>
【讨论】:
以上是关于JS中的对象设置器未定义的主要内容,如果未能解决你的问题,请参考以下文章
自定义渲染器未应用于 Table 渲染 handsontable
如何解决 Bootstrap node.js 应用程序中的错误“无法设置未定义的属性 'emulateTransitionEnd'”?