Questions:
- can any one tell me what is the use of declaring constructor?
- Is that a best practice?
- In case if I am not declaring the constructor what is the issue i will be getting?
- what are the ways for declaring constructors?
Answers:
[A1] in some scenarios, it is necessary to find out the instance's real constructor, especially inheritance level is deep. e.g. https://github.com/chennanfei/ThinkMVC/blob/master/thinkmvc.js#L737. In a word, to know the exact construtor of instances is helpful for some cases.
[A2] As Johan pointed out,
Ferari.prototype = Object.create(Ferari.prototype);
Ferari.prototype.constructor = Ferari;
[A3] I don't think you will get issues unless you use it obviously.
[A4] Your code indicates the general way. I think following way works, too.
var Cart = function() {...}
To answer Johan's question in the comment, I added more here. (text's size is limited in comment.)
here is a little complex case. Suppose the 'class' Base provides a method 'setProtoValue' which allows instances to set/update the properties of their prototype. Classes A and B inherit from Base. When A's instances call the method 'setValue', of course we don't hope affect all B's instances. So we need know the exact constructor of A. In following example, if we don't reset A.prototype.constructor, all Base instances including B will be affected which is unexpected.
var Base = function() {};
Base.prototype.setProtoValue = function(key, value) {
this.constructor.prototype[key] = value;
};
var A = function() {};
A.prototype = Object.create(Base.prototype);
A.prototype.constructor = A;
var B = function() {};
B.prototype = Object.create(Base.prototype);
B.prototype.constructor = B;