如何在对象内部访问自身属性?自定义Alert框异常求助
问题解答
1. 标题和消息显示undefined的原因及修复方案
你遇到的第一个问题,核心是静态字符串模板不会动态更新。你的snippet是在alerter对象初始化时就生成的固定字符串,此时${this.title}和${this.message}已经被计算成初始值(或者初始化时的undefined)。当你在show方法里更新title和message后,旧的snippet字符串并不会自动同步新值。
解决办法是把snippet改成一个动态生成HTML的函数,每次调用show时再生成最新的内容,这样就能拿到更新后的属性值:
let alerter = { status: false, title: "AlerterTitle", message: "This is a small alert!", // 改成函数,每次调用都生成最新的HTML片段 getSnippet: function() { return `<div id="alerter"> <div class="alerter-title">${this.title}</div> <div class="alerter-body">${this.message}</div> <button id="alerter-close">Close</button> </div>`; }, show: function(message, title = "Alert") { if (this.status) { return true; } this.status = true; this.title = title; this.message = message; // 调用函数获取最新的HTML document.body.innerHTML += this.getSnippet(); const closeBtn = document.querySelector("#alerter-close"); closeBtn.addEventListener("click", function() { let alertBox = document.querySelector("#alerter"); document.body.removeChild(alertBox); alerter.status = false; }) } }
2. 为什么不能用this.status代替alerter.status
这是JavaScript中this指向的典型问题:
你给关闭按钮绑定的是普通函数作为事件回调,在这个函数里,this的指向是触发事件的DOM元素(也就是那个#alerter-close按钮),而不是alerter对象。所以你写this.status时,实际上是在找按钮元素的status属性——这个属性根本不存在,自然无法修改alerter的状态。
如果想在回调里用this指向alerter,有两种常用方案:
- 使用箭头函数:箭头函数不会绑定自己的
this,会继承外层作用域的this(也就是show方法里的this,指向alerter)
closeBtn.addEventListener("click", () => { let alertBox = document.querySelector("#alerter"); document.body.removeChild(alertBox); this.status = false; // 此时this指向alerter })
- 用
bind绑定this:手动把alerter对象绑定到回调函数的this上
closeBtn.addEventListener("click", function() { let alertBox = document.querySelector("#alerter"); document.body.removeChild(alertBox); this.status = false; }.bind(this)); // 这里的this是show方法里的alerter对象
内容的提问来源于stack exchange,提问作者mzmarkib
相关产品推荐
相关产品推荐

