JavaScript прототипы и прототипное наследование
<script>
// Прототипы и наследование
// Функция Auto
function Auto (brand, price, gas){
this.brand = brand;
this.price = price;
this.gas = gas;
}
// Прототип функции Auto ЗНАЧИТЕЛЬНО уменьшает использование памяти
// Функция одинакова для всех экземпляров
Auto.prototype.drive = function(){
if (this.gas > 0) {
this.gas = this.gas - 20;
return this.gas;
} else {
console.log('Бензин закончился!');
}
}
// Прототип, как общее свойство для всех экземпляров
Auto.prototype.discount = 0.7;
const bmw = new Auto('BMW', 1000, 100);
const nissan = new Auto('Nissan', 4000, 100);
// console.log(bmw);
console.log(nissan.discount);
</script>
Комментарии
Отправить комментарий