javascript - 传递“这个”的麻烦
问题描述
抱歉标题不好,我真的不知道如何提出我的问题。
下面的代码是我正在做的事情的一小部分,它可以自动生成与游戏的点击事件配对的按钮。我试图将modal.load()
函数(它以关联数组作为参数)作为字符串传递给"Look"
按钮。那么函数传递工作(它不在提供的代码中),但是
可以看到,actions[0].script
returns的每个属性undefined
,好像this
没有通过..
告诉我您是否需要其他任何东西来理解代码。
actions = [{
name: "Look",
modal_color: 'salmon',
modal_img: '',
modal_title: 'This is a title',
modal_text: 'This is text',
script: `modal.load({'img': '${this.modal_img}', 'color': '${this.modal_color}', 'title': '${this.modal_color}', 'txt': '${this.modal_text}'});`,
},
{
name: "Walk",
script: "console.info('Other type of script')"
}
]
console.log(actions[0].script)
编辑:为清楚起见模板字符串
解决方案
"this" 仅适用于功能范围,不适用于对象范围
actions = [{
name: "Look",
modal_color: 'salmon',
modal_img: '',
modal_title: 'This is a title',
modal_text: 'This is text',
script: function(){
return `modal.load({'img': '${this.modal_img}', 'color': '${this.modal_color}', 'title': '${this.modal_color}', 'txt': '${this.modal_text}'});`;
}},
{
name: "Walk",
script: "console.info('Other type of script')"
}
]
console.log(actions[0].script())
推荐阅读
- azure - 使用 Perl、HTTP、LWP 了解我的授权标头有什么问题
- jenkins - dynamicStage 和 dynamicAlwaysScript 关键字的目的是什么
- python - Quantlib Svensson 拟合问题
- nextflow - 使用 nextflow 拆分配对的 fasta 文件
- python - 我什么时候可以使用“conda install”,什么时候必须使用“pip install”
- excel - 如何根据条件对单元格进行颜色编码?
- spring-boot - 从 Spring Cloud Greenwich.SR1 更新到 SR2 后,h2-console 停止工作
- c# - Selenium .NET core 2.2 发布的项目 exe 即使在 Windows x64 上也无法运行
- vba - 当用户切换到下一个控件时,移动子窗体的代码或属性是什么?
- sql - 防止在批量查询中除以零