This sample achieves private variables of rectangle. The variables myLength and myWidth are different for different instances. So why is this not recommended approach?
var rectangle = function() {
var myLength = 8;
var myWidth = 6;
var getMyLength = function () {
return myLength;
};
var setMyLength = function (value) {
myLength = value;
};
var getMyWidth = function () {
return myWidth;
};
var setMyWidth = function (value) {
myWidth = value;
};
var drawFigure = function() {
console.log("Draw invoked for figure: " +
getMyLength() + " * " + getMyWidth());
};
return {
getMyLength: getMyLength,
setMyLength: setMyLength,
getMyWidth: getMyWidth,
setMyWidth: setMyWidth,
drawFigure: drawFigure
}
};
Then we use it as follows:
var myRectangle = new rectangle();
myRectangle.drawFigure(); // Draw invoked for figure: 8 * 6
myRectangle.setMyLength(3);
myRectangle.setMyWidth(5);
myRectangle.drawFigure(); // Draw invoked for figure: 3 * 5
var myRectangle1 = new rectangle();
myRectangle1.drawFigure(); // Draw invoked for figure: 8 * 6