I\'m new to JavaScript and I\'m trying to wrap my head around creating \"classes\" with private data and public functions. I\'ve been told Immediately Invoked Function Expre
var Car =
( function ( cardb ) {
function Car ( color ) {
// facing the same problem here
// reinstaling .data() method for each created object
// but this way each has its own data store object
// and inner 1 to 1 circular reference js is able to deal with
cardb( this );
// set provided color parameter
this.data("color", color);
}
return Car;
} )(
// function to install .data() method to given object
// it gets attached to object directly, instead of
// attaching it to .prototype, in which case all
// object will access same data store
function ( obj ) {
var _data = {};
obj.data =
function ( name, value ) {
return arguments.length
? (
( value == null )
? _data[name]
: (
_data[name] = value,
this
)
)
: _data;
};
return obj;
}
);
var c1 = new Car("red");
var c2 = new Car("blue");
c1.data("color");
// red
c2.data("color");
// blue
c1.data("color","white");
c2.data("color");
// blue
c1.data("color");
// white
//