LoginSignup
0
0

【JavaScript】文字列を変数名として認識させてみる

Posted at

はじめに

Blazor で、ExcelライクなグリッドJSライブラリのHandsontableを使用しています。

Blazor では JavaScript から C# を呼ぶことができます。一般的には WindowsオブジェクトにDotNetが予め定義されているため、「DotNet.invokeMethodAsync(C#に定義したメソッド)」のように呼びます。
この方法では、複数台で操作した時に問題が発生しました。

その際に WindowsオブジェクトにDotNetの代わりとして、ComponentReferenceを定義した上で、「ComponentReference.invokeMethodAsync(C#に定義したメソッド)」としました。

export class SpreadSheet {
  constructor(reference) {
    window.ComponentReference = reference;
  }

  // インスタンス作るためのメソッド
  static create(reference) {
    return new SpreadSheet(reference);
  }

問題

画面上に、このコンポーネントを利用した履歴一覧表示とチェックシート一覧表示が両方表示される状態になった場合、履歴一覧で全選択チェック処理(C#メソッドを呼ぶ)を呼ぶと JavaScriptエラーが発生していることが分かりました。

原因として、window.ComponentReferenceの変数が被っているため、チェックシート一覧表示がされた段階で変数内容が上書きされてしまい、履歴一覧表示側の全選択チェック処理が呼べない状態となっていました。

対応

window.ComponentReferenceの変数が被らないように、
履歴一覧表示は、window.HisotryListReference
チェックシート一覧表示はwindow.CheckSheetListReference
と分けました。

本題

コンポーネントに変数用の文字列を引数として渡して変数名にできるのなら、より汎用的なコンポーネントに出来る。
そもそも、文字列を変数名として認識できるんだっけ?

Chat GPTに聞いてみた

JavaScriptで文字列を変数名として認識できますか

JavaScriptでは文字列を変数名として動的に扱うことができます。ただし、通常の変数名としてではなく、オブジェクトのプロパティとして扱う方法を使います。

以下に、いくつかの方法を紹介します。

1. オブジェクトのプロパティとして使用

JavaScriptでは、オブジェクトのプロパティに文字列を使うことができます。オブジェクトのプロパティにアクセスする際に、ドット記法 (object.property) のほかに、ブラケット記法 (object['property']) を使用することで、文字列をプロパティ名として扱えます。

let variableName = "dynamicVariable";
let obj = {};

obj[variableName] = "This is a dynamically named variable";

console.log(obj.dynamicVariable);  // "This is a dynamically named variable"
console.log(obj[variableName]);    // "This is a dynamically named variable"

2. eval 関数を使う方法

eval 関数を使うと、文字列をJavaScriptコードとして評価し実行できますが、この方法はセキュリティやパフォーマンスの観点から推奨されません。

let variableName = "dynamicVariable";
eval('var ' + variableName + ' = "This is a dynamically named variable"');

console.log(dynamicVariable);  // "This is a dynamically named variable"

3. window オブジェクトを使う方法 (ブラウザ環境の場合)

ブラウザのグローバルスコープでは、window オブジェクトを使用して動的に変数を作成することもできます。

let variableName = "dynamicVariable";
window[variableName] = "This is a dynamically named variable";

console.log(window.dynamicVariable);  // "This is a dynamically named variable"
console.log(window[variableName]);    // "This is a dynamically named variable"

まとめ

オブジェクトのプロパティとして文字列を使う方法が最も一般的で安全です。eval 関数の使用は避けた方が良いでしょう。ブラウザ環境では、window オブジェクトを使うこともできますが、これはグローバル変数を操作するため、注意が必要です。

最後に

採用するかは別として、出来ることは把握しました。

export class SpreadSheet {
  constructor(variable, reference) {
    window[variable] = reference;
  }

  // インスタンス作るためのメソッド
  static create(variable, reference) {
    return new SpreadSheet(variable, reference);
  }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0