개체를 인스턴스 개체로 캐스팅하고 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!