简体   繁体   English

将函数参数插值到新的变量声明中

[英]Interpolate a function argument into a new variable declaration

I have a function that will create a new chart to be displayed in HTML. 我有一个函数,它将创建一个新的图表以HTML显示。 I'd like to call the function with some arguments to be interpolated into the chart's variable declaration like this: 我想使用一些要插入到图表的变量声明中的参数来调用该函数,如下所示:

function createChart(category, name) {
    const {category}{name}Chart = new Chart();
}

What is the right way to do this? 什么是正确的方法?

Here's one possible solution: 这是一种可能的解决方案:

var charts = {};
function createChart(category, name) {
    if (!charts[category]) charts[category] = {};
    charts[category][name] = new Chart();
}

Using the new operator will make this a constructor call which will implicitly return a new object. 使用new运算符将使它成为一个constructor调用,它将隐式返回一个新对象。
this means you can use the this key word to "attach" properties to this new object via parameters you pass as arguments. 这意味着您可以使用this关键字通过作为参数传递的参数将属性“附加”到该新对象。

Example: 例:

 function Chart(category, name) { this.category = category; this.name = name; } const chart = new Chart('some category', 'John Doe'); console.log(chart); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM