JavaScript类构造函数属性填充HTML模板出现undefined如何解决
问题原因
你代码的问题出在JavaScript公有类字段的初始化顺序:直接定义在类体中的secret字段会在constructor执行之前完成初始化,此时你还没给this.title和this.typeOfSecret赋值,所以模板插值得到的结果是undefined。
解决方案
方案1:将模板赋值移到constructor中
这是改动最小的方案,确保赋值时实例属性已经完成初始化:
class Secret { constructor(title, typeOfSecret) { this.title = title this.typeOfSecret = typeOfSecret // 此时实例属性已赋值,插值正常 this.secret = `<div class="secret"> <p class="title secret-title">${this.title}</p> <div class="secret-message ${this.typeOfSecret}"> <p class="text-inside black">${this.typeOfSecret}</p> </div> <button class="hack">hack</button> </div>` } append() { console.log(this.secret) elementsContainer.innerHTML += this.secret } }
方案2:将secret改为getter方法
如果需要支持属性修改后自动更新模板内容,可以把secret定义为getter,只有访问时才会动态生成模板:
class Secret { constructor(title, typeOfSecret) { this.title = title this.typeOfSecret = typeOfSecret } // 访问.secret时才执行插值逻辑 get secret() { return `<div class="secret"> <p class="title secret-title">${this.title}</p> <div class="secret-message ${this.typeOfSecret}"> <p class="text-inside black">${this.typeOfSecret}</p> </div> <button class="hack">hack</button> </div>` } append() { console.log(this.secret) elementsContainer.innerHTML += this.secret } }
安全提示
如果title或typeOfSecret是用户可控的输入内容,直接通过innerHTML插入存在XSS注入风险,建议先对内容做HTML转义,参考转义函数:
function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'") }
使用时将插值部分替换为${escapeHtml(this.title)}即可。
内容的提问来源于stack exchange,提问作者Abdulrahman Azmy
相关产品推荐
相关产品推荐

