Three-part question:
Any value to adding a second layer of abstraction, and using a prototype getter/setter function to invoke privileged constructor getter/setter functions? See
ns.Wheel.prototype.getWeight2()andns.Wheel.prototype.setWeight2()below.The call to
swiss.getWeight()invokes thethis.getWeight()method in the constructor. Any way to move one level up the prototype chain to instead invokens.Wheel.prototype.getWeight()?Any value to "hiding" the prototype getter/setter functions "behind" the constructor getter/setters? E.g.,
ns.Wheel.prototype.getWeight()is "hidden" behind thethis.getWeight()method in the constructor.
Also note how the prototype getter/setters add the unit for grams; i.e., "g" unit. E.g., this.getWeight returns 1000, while ns.Wheel.prototype.getWeight returns 1000g.
Wheels of swiss cheese are used in this example.
(function(ns) {
ns.Wheel = function() {
var _weight = 1000; // weight of cheese wheel. Private variable.
this.getWeight = function() { return _weight } // privileged weight getter
this.setWeight = function(weight) { return _weight = weight } // privileged weight setter
}
ns.Wheel.prototype.getWeight = function() { return this.getWeight()+'g' }
ns.Wheel.prototype.setWeight = function(weight) { return this.setWeight(weight)+'g' }
ns.Wheel.prototype.getWeight2 = function() { return this.getWeight()+'g' }
ns.Wheel.prototype.setWeight2 = function(weight) { return this.setWeight(weight)+'g' }
})(window.cheese = window.cheese || {}); // immediate function namespacing technique
var swiss = new cheese.Wheel();
console.log(swiss.getWeight()); //-> 1000. Invokes constructor method
console.log(swiss.setWeight(2000)); //-> 2000. Invokes constructor method
console.log(swiss._weight); //-> undefined. Private variable!!!
console.log(swiss.getWeight2()); //-> 2000g. Invokes prototype method.
console.log(swiss.setWeight2(9000)); //->9000g. Invokes prototype method.