MENU
Being a Class Constructor
A function can be used as a constructor for a new user-defined data type. This technique, however, has been superseded by Class (8.6).
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function rectangle(a,b){
this.width=a;
this.height=b;
this.area=function(){return this.width*this.height;}}rectangle.prototype.perimeter =
function(){return 2*(this.width+this.height);}rectangle.standardArea = 100; // 'static' variablerectangle.findAreaFromSideLengths =
(a,b)=>{return a*b;}; // 'static' functionvar r=new rectangle(10,20);r.height=30;console.log(r.area()); // 300console.log(r.perimeter()); // 80console.log(rectangle.standardArea); // 100console.log(rectangle.findAreaFromSideLengths(5,6)); // 30
</script></body><html>
A property declared inside the constructor with 'this' is preferred over one declared outside with 'prototype'.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function C(){this.p=10;}C.prototype.p = 100;var a = new C;var b = new C;console.log(a.p); // 10//console.log(a.prototype.p); // TypeErrorconsole.log(C.p); // undefinedconsole.log(C.prototype.p); // 100b.p = 300;console.log(a.p); // 10
</script></body><html>
There is a subtle difference between a method defined inside the constructor and a method defined outside with prototype. The former is assigned to every instance of the class, whereas the latter is shared by all instances.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function C1(){
this.M = ()=>{console.log(1);}
this.changeM = ()=>{this.M = ()=>{console.log(2);}}}var a = new C1;var b = new C1;a.M(); // 1a.changeM();b.M(); // 1
</script></body><html>
<!DOCTYPE html><html><body><script>
function C2(){}C2.prototype.M = ()=>{console.log(1);}C2.prototype.changeM = ()=>{C2.prototype.M = ()=>{console.log(2);}}var a = new C2;var b = new C2;a.M(); // 1a.changeM();b.M(); // 2
</script></body><html>
Hence, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods defined internally would get reassigned (that is, for every object creation).
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function myobject(){this.value = 5;}myobject.prototype.add = function(){ this.value++; }function objectchanger(fnc){ fnc(); }var o = new myobject();objectchanger(o.add);console.log(o.value); // 6
</script></body><html>
A function is also an object, although typeofwill return it as 'function'.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
console.log((()=>{}).a=10); // 10console.log(typeof (()=>{})); // function
</script></body><html>