この問題を解決する一般的な方法は、Object ( ) に、DTO ( Data Transfer Object )を受け入れて新しいインスタンスを返すcData
静的ファクトリ メソッドを提供することです。cData
function cData() {
this.Email = "";
this.Name = "";
this.test = function () {
alert("lol");
}
}
// Static factory which produces a new `cData` object from the supplied
// Data Transfer Object. Note this function belongs to the Constructor
// function rather than instances created when it's used.
cData.fromDTO(value) {
// Create a new cData instance.
var result = new cData();
// Copy the properties from the DTO.
result.Email = value.Email;
result.Name = value.Name;
// Return the populated instance.
return result;
}
次に、静的ファクトリを使用して、AJAX 呼び出しの結果を処理できます。つまり、次のようになります。
function onAjaxResponse(response) {
var myData = cData.fromDTO(JSON.parse(response));
// Invoke the 'test' method.
myData.test();
}
これにより、データ トランスポート層 (サーバーからのデータ) とビジネス ロジック (JavaScript アプリケーション) が明確に分離されます。DTO のプロパティを変更する必要がある場合 (例:にName
変更FirstName
)、コードを 1 か所 (fromDTO
ファクトリ メソッド) で変更するだけで済みます。
補足として、コンストラクター関数に名前を付けるときは、BumpyCaps を使用することを検討する必要があります(つまり、最初の文字は大文字にする必要があります。つまりMyClass
、myClass
他の関数とは異なります)。