With didactic interest I would like to know a right way to simulate autoincrement variable on object creation.
I place you in scene where I ve got a encapsulated Product """"class"""" as an object with hidden attributes.
(function() {
var Product = (function() {
function Product(name, description) {
this.getName = function() {
return name;
};
this.getDescription = function() {
return description;
};
this.getProductId = function() {
return productId;
}
}
return Product;
}());
var p = new Product("Product1", "Should have id=1");
var q = new Product("Product2", "Should have id=2");
console.log(p);
console.log(q);
})();
Over this code how or what is the best way to add a counter so that every time I create a new instance of the Product then productId is going to have consecutive value and every object preserve his own. At the same time that said Id is only accessible through the method getProductId().
Thanks in advance.
You could make use of Closures:
(function() {
var Product = (function() {
var nextId = 1;
function Product(name, description) {
var productId = nextId;
nextId += 1;
this.getName = function() {
return name;
};
this.getDescription = function() {
return description;
};
this.getProductId = function() {
return productId;
}
}
return Product;
}());
var p = new Product("Product1", "Should have id=1");
var q = new Product("Product2", "Should have id=2");
console.log(p.getProductId());
console.log(q.getProductId());
})();
If you wrap a function in another function, the inner function has access to all the variables of the outer functions. When you create a new Product
, function Product(name, description)
is called; each time incrementing nextId by 1. If you want to see many more examples on closures, you could take a look at this stackoverflow answer.