オブジェクトをインスタンス オブジェクトにキャストし、JavaScript 配列でメソッドの使用を有効にする方法

Patricia Arquette
リリース: 2024-10-18 12:22:30
オリジナル
261 人が閲覧しました

How to Cast Objects to Instance Objects and Enable Method Use in JavaScript Arrays?

Casting Objects to Class Instances in JavaScript

Question:

How can I cast a generic object array (e.g., [{personName: 'John', animals: []}]) received from a server to a typed array of objects (e.g., [Person(personName: 'John', animals: [])]), allowing for method use (e.g., persons[0].animals[2].run())?

Answer:

Creating class instances in JavaScript requires invoking the constructor with the correct arguments (not just properties). We provide two solutions:

Method 1: Static Method for Cloning

Define a static method on the class that takes objects and creates instances from them, for example:

<code class="javascript">Person.fromJSON = function(obj) {
  // Custom code for Person instances
  return new Person();
};</code>
ログイン後にコピー

Method 2: Object Cloning

Clone the properties from the JSON-parsed object to a new instance, for example:

<code class="javascript">var personLiteral = JSON.parse("...");
var personInstance = new Person();
for (var prop in personLiteral)
  personInstance[prop] = personLiteral[prop];</code>
ログイン後にコピー

Or, using Object.assign:

<code class="javascript">var personInstance = Object.assign(new Person(), personLiteral);</code>
ログイン後にコピー

Example for Your Case:

In your specific case, you have a simple object structure with no arguments and only public properties. To convert to an object instance:

<code class="javascript">var persons = JSON.parse(serverResponse);
for (var i=0; i&lt;persons.length; i++) {
  persons[i] = $.extend(new Person, persons[i]);
  for (var j=0; j&lt;persons[i].animals; j++) {
    persons[i].animals[j] = $.extend(new Animal, persons[i].animals[j]);
  }
}</code>
ログイン後にコピー

Note: The run method should likely be added to the Animal.prototype object instead of each instance.

以上がオブジェクトをインスタンス オブジェクトにキャストし、JavaScript 配列でメソッドの使用を有効にする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!