Answer the question
In order to leave comments, you need to log in
What do these lines of code in the task do?
Hello! Please help me understand the code.
Assignment (taken from the tutorial):
Override the disable method of the refrigerator so that it will throw an error if there is food in it.
Please explain the meaning of these lines of code in the problem
In all honesty
1)
Does this code play any role in the Machine constructor?
this.disable = function() {
self._enabled = false;
};
2)
What is var parentDisable = this.disable; and its call to parentDisable();
function Machine(power) {
this._power = power;
this._enabled = false;
var self = this;
this.enable = function() {
self._enabled = true;
};
this.disable = function() {
self._enabled = false;
};
}
function Fridge(power) {
Machine.apply(this, arguments);
var food = []; // приватное свойство food
this.addFood = function() {
if (!this._enabled) {
throw new Error("Холодильник выключен");
}
if (food.length + arguments.length >= this._power / 100) {
throw new Error("Нельзя добавить, не хватает мощности");
}
for (var i = 0; i < arguments.length; i++) {
food.push(arguments[i]); // добавить всё из arguments
}
};
this.getFood = function() {
// копируем еду в новый массив, чтобы манипуляции с ним не меняли food
return food.slice();
};
this.filterFood = function(filter) {
return food.filter(filter);
};
this.removeFood = function(item) {
var idx = food.indexOf(item);
if (idx != -1) food.splice(idx, 1);
};
var parentDisable = this.disable;
this.disable = function() {
if (food.length) {
throw new Error("Нельзя выключить: внутри еда");
}
parentDisable();
};
}
var fridge = new Fridge(500);
fridge.enable();
fridge.addFood("кус-кус");
fridge.disable(); // ошибка, в холодильнике есть еда
Answer the question
In order to leave comments, you need to log in
Does this code play any role in the Machine constructor?Of course, he plays - otherwise he would not be in the textbook.
What is var parentDisable = this.disable; and its call to parentDisable();On the next line, this.disable is overridden by its own logic, so you need to keep the parent functionality in order to use it and avoid duplicating logic.
Yes, he plays. This is the principle of inheritance. The refrigerator inherits parameters and methods from the mechanism, but at the same time overrides them, and in order not to lose connection with the mechanism, it saves its parameters separately. These are the basic things to learn. Here it is immediately clear that there is no knowledge and ability to apply them. Need to study!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question