Прототипы JavaScript


Оглавление

    Показать оглавление


Все объекты JavaScript наследуют свойства и методы. из прототипа.


В предыдущей главе мы узнали, как использовать конструктор объекта:

Пример

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");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>Using an object constructor:</p>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age; 
</script>

</body>
</html>

Мы также узнали, что вы можете не добавлять новое свойство в существующий конструктор объекта:

Пример

Person.nationality = "English";

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>You cannot add a new property to a constructor function.</p>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.nationality = "English";

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality; 
</script>

</body>
</html>

Чтобы добавить новое свойство в конструктор, вы должны добавить его в функция конструктора:

Пример

function Person(first, last, age, eyecolor) {
   
this.firstName = first;
   
this.lastName = last;
   
this.age = age;
   
this.eyeColor = eyecolor;
  this.nationality = "English";
}

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Objects</h1>

<p>Using an object constructor:</p>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
  this.nationality = "English";
}

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality + ". The nationality of my mother is " + myMother.nationality;
</script>

</body>
</html>


Наследование прототипа

Все объекты JavaScript наследуют свойства и методы прототипа:

  • Объекты Date наследуются от Date.prototype

  • Объекты Array наследуются от Array.prototype

  • Объекты Person наследуются от Person.prototype

Object.prototype находится на вершине цепочки наследования прототипа:

Объекты Дата, объекты Массив и Человек объекты наследуются от Object.prototype.


Добавление свойств и методов к объектам

Иногда вам нужно добавить новые свойства (или методы) ко всем существующим объектам данного типа.

Иногда вам нужно добавить к объекту новые свойства (или методы). конструктор.


Использование свойства prototype

Свойство JavaScript prototype позволяет добавлять к объекту новые свойства. конструкторы:

Пример

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}

 Person.prototype.nationality = "English";

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>The prototype property allows you to add new methods to objects constructors:</p>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.nationality = "English";

const myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality; 
</script>

</body>
</html>

Свойство JavaScript prototype также позволяет добавлять к объектам новые методы. конструкторы:

Пример

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;
};

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.name = function() {
  return this.firstName + " " + this.lastName
};

const myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"My father is " + myFather.name(); 
</script>

</body>
</html>

Изменяйте только свои собственные прототипы. Никогда не изменяйте прототипы стандартные объекты JavaScript.