Introduction
Constructors in JavaScripts! Sounds odd. Right?
But yes Constructors in JavaScripts are widely used by developers nowadays. And you too should consider it, as it may help you make your code neat.
Enough Gyan! Lets code
- function Programmer(id, name) {
- this.id = id;
- this.name = name;
- this.describe = function () {
- console.log(this.name + “hates javascript!”);
- }
- }
- var m = new Programmer(“Bill”, 420);
- console.log(m);
Note: Capital P in Programmer, this is the notion used for constructors, first capital alphabet.
The above code creates an object and assigns appropriate values to it using the self-defined constructor.
Role of new keyword
- Creates an empty object which is referenced by “this” keyword which inherits the prototype of the function.
- Returns object referred by this if no object is returned explicitly.
We can imagine the role of a new keyword as
- function Programmer(id, name) {
-
-
- this.id = id;
- this.name = name;
- this.describe = function () {
- console.log(this.name + “hates javascript!”);
- }
-
-
- }
That simple
Another thing which you will want to consider while creating constructors will be exploiting the prototype property of a constructor.
JavaScript is sloppy, no doubt! But by following goods patterns you can write manageable code.