This question is an exact duplicate:
There is such code, found in the book on js. There are no errors in this example. everything is displayed as it should and output 450
'use strict'; function CoffeeMachine(power, capacity) { var waterAmount = 0; this.waterAmount = function(amount) { if(!arguments.length) return waterAmount; if(amount < 0) { throw new Error('Значение должно быть положительным!'); } if(amount > capacity) { throw new Error('Значение не должно быть больше ' + capacity); } waterAmount = amount; }; } var coffeeMachine = new CoffeeMachine(1000, 500); coffeeMachine.waterAmount(450); alert(coffeeMachine.waterAmount()); But in this example, undefined is displayed.
'use strict'; function CoffeeMachine(power, capacity) { var waterAmount = 0; this.waterAmount = function(amount) { if(!arguments.length) return waterAmount; if(amount < 0) { throw new Error('Значение должно быть положительным!'); } if(amount > capacity) { throw new Error('Значение не дожно быть больше ' + capacity); } waterAmount = amount; }; } var coffeeMachine = new CoffeeMachine(1000, 500); alert(coffeeMachine.waterAmount(450)); Then I just recorded the alert immediately and that's it. explain what is the difference, why when it is not recorded in the alert then everything works, but on the contrary it does not.
coffeeMachine.waterAmount(450)andcoffeeMachine.waterAmount()- there is a difference. - nick_n_a February