javascript use method in constructor code example
Example 1: constructor in js
A constructor is a function that creates an instance of a class
which is typically called an “object”. In JavaScript, a constructor gets
called when you declare an object using the new keyword.
The purpose of a constructor is to create an object and set values if
there are any object properties present.
Example 2: javascript prototype vs constructor function
function Class () {}
Class.prototype.calc = function (a, b) {
return a + b;
}
var ins1 = new Class(),
ins2 = new Class();
console.log(ins1.calc(1,1), ins2.calc(1,1));
Class.prototype.calc = function () {
var args = Array.prototype.slice.apply(arguments),
res = 0, c;
while (c = args.shift())
res += c;
return res;
}
console.log(ins1.calc(1,1,1), ins2.calc(1,1,1));
Example 3: how to create a constructor in javascript
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
let blueBird = new Bird();