Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách truy cập object JavaScript bằng prototype của chính nó

Truy cập object hiện có bằng cách tạo prototype của nó với Object.create(). Property được kế thừa từ object gốc sang prototype mới.

Cú pháp

Object.create(existingObject);

Ví dụ

<html> <body> <script>    var person = {       name: "Karthee",       profession: "Actor",       industry: "Tamil"    };    document.write(person.name + "<br>");    document.write(person.profession + "<br>");    document.write(person.industry + "<br>");    document.write("Using prototype changed properties:<br>"); var newper = Object.create(person); newper.name = "sachin"; newper.profession = "cricketer"; newper.industry = "sports"; document.write(newper.name + "<br>"); document.write(newper.profession + "<br>"); document.write(newper.industry); </script> </body> </html>

Kết quả

Karthee Actor Tamil Using prototype changed properties: sachin cricketer sports

Giải thích:

  • Object.create(proto) tạo object mới với [[Prototype]] = proto
  • newper kế thừa property từ person (prototype chain)
  • Gán newper.name = 'sachin' tạo own property che property prototype
  • Đọc property: tìm own property trước, rồi lên prototype chain
  • Đây là cơ chế prototypal inheritance cốt lõi của JS