JavaScript Prototypes

JavaScript Prototypes



all javascript objects inherit properties and methods from a prototype.


in the previous chapter we learned how to use an object constructor:

Quý khách đang xem: JavaScript Prototypes

example

function person(first, last, age, eyecolor)
  this.firstname = first;
  this.lastname = last;
  this.age = age;
  this.eyecolor = eyecolor;

const myfather = new person(“john”, “doe”, 50, “blue”);
const mymother = new person(“sally”, “rally”, 48, “green”);

try it yourself »

we also learned that you can not add a new property to an existing object constructor:

to add a new property to a constructor, you must add it to the constructor function:

Xem nhiều hơn: Cinnamon Là Gì Và Cách Sử Dụng Cinnamon

example

function person(first, last, age, eyecolor)
  this.firstname = first;
  this.lastname = last;
  this.age = age;
  this.eyecolor = eyecolor;
  this.nationality = “english”;

try it yourself »



prototype inheritance

all javascript objects inherit properties and methods from a prototype:

  • date objects inherit from date.prototype
  • array objects inherit from array.prototype
  • person objects inherit from person.prototype

the object.prototype is on the top of the prototype inheritance chain:

date objects, array objects, and person objects inherit from object.prototype.


adding properties and methods to objects

sometimes you want to add new properties (or methods) to all existing objects of a given type.

sometimes you want to add new properties (or methods) to an object constructor.


using the prototype property

the javascript prototype property allows you to add new properties to object constructors:

example

function person(first, last, age, eyecolor)
  this.firstname = first;
  this.lastname = last;
  this.age = age;
  this.eyecolor = eyecolor;

person.prototype.nationality = “english”;

Xem nhiều hơn: [Nhâm Thân 1992] Sinh năm 1992 mệnh gì, tuổi gì, sinh năm 1992 bao nhiêu tuổi, hợp với tuổi nào?

try it yourself »

the javascript prototype property also allows you to add new methods to objects constructors:

example

function person(first, last, age, eyecolor)
  this.firstname = first;
  this.lastname = last;
  this.age = age;
  this.eyecolor = eyecolor;

person.prototype.name = function()
  return this.firstname + ” ” + this.lastname;
;

try it yourself »

only modify your own prototypes. never modify the prototypes of standard javascript objects.



Nguồn gốc: https://danhgiaaz.com
danh mục: Kinh nghiệm – Hướng dẫn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *