Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

자체 프로토타입을 사용하여 JavaScript 객체에 액세스하는 방법은 무엇입니까?


기존 개체에 액세스할 수 있습니다. t "Object.create()라는 자바스크립트 메소드를 사용하여 자체 프로토타입을 생성 ". 이 방법을 사용하면 기존 속성에서 새로 생성된 프로토타입으로 속성을 상속할 수 있습니다. 간단히 설명하겠습니다.

구문

Object.create(existing obj);

이 메서드는 기존 개체를 사용하고 속성이 상속되도록 자체 프로토타입을 만듭니다. 기존 개체에서 새로 생성된 프로토타입으로 .

예시

다음 예에서는 처음에 "사람이라는 개체가 "가 생성되고 "Object.create를 사용하여 " 자체 프로토타입이 생성되어 "newper 변수에 할당됩니다. ". 나중에 프로토타입을 사용하여 기존 개체의 개체가 변경되고 새 속성이 출력과 같이 표시되었습니다.

<html>
<body>
<script>
   var person = {
      name: "Karthee",
      profession : "Actor",
      industry: "Tamil"
   };
   document.write(person.name);
   document.write("</br>");
   document.write(person.profession);
   document.write("</br>");
   document.write(person.industry);
   document.write("</br>");
   document.write("Using a prototype the properties of the existing object have been 
   changed to the following");
   document.write("</br>");
   var newper = Object.create(person); /// creating prototype
   newper.name = "sachin";
   newper.profession = "crickter";
   newper.industry = "sports";
   document.write(newper.name);
   document.write("</br>");
   document.write(newper.profession);
   document.write("</br>");
   document.write(newper.industry);
</script>
</body>
</html>

출력

Karthee
Actor
Tamil
Using a prototype the properties of the existing object have been changed to the following
sachin
crickter
sports