首页 > 解决方案 > 传递“这个”的麻烦

问题描述

抱歉标题不好,我真的不知道如何提出我的问题。

下面的代码是我正在做的事情的一小部分,它可以自动生成与游戏的点击事件配对的按钮。我试图将modal.load()函数(它以关联数组作为参数)作为字符串传递给"Look"按钮。那么函数传递工作(它不在提供的代码中),但是

可以看到,actions[0].scriptreturns的每个属性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)

编辑:为清楚起见模板字符串

标签: javascriptobject

解决方案


"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())


推荐阅读